timmy a révisé ce gist 10 months ago. Aller à la révision
Aucun changement
timmy a révisé ce gist 10 months ago. Aller à la révision
Aucun changement
timmy a révisé ce gist 10 months ago. Aller à la révision
Aucun changement
timmy a révisé ce gist 10 months ago. Aller à la révision
1 file changed, 66 insertions
disk_usage_http_server.py(fichier créé)
| @@ -0,0 +1,66 @@ | |||
| 1 | + | import json | |
| 2 | + | from http.server import BaseHTTPRequestHandler, HTTPServer | |
| 3 | + | from urllib.parse import urlparse, parse_qs | |
| 4 | + | import shutil | |
| 5 | + | ||
| 6 | + | ||
| 7 | + | class DiskUsage: | |
| 8 | + | def __init__(self, path="/"): | |
| 9 | + | self.path = path | |
| 10 | + | ||
| 11 | + | def get_usage(self): | |
| 12 | + | try: | |
| 13 | + | total, used, free = shutil.disk_usage(self.path) | |
| 14 | + | usage_percent = (used / total) * 100 if total > 0 else 0 | |
| 15 | + | return { | |
| 16 | + | "path": self.path, | |
| 17 | + | "total_space": total, | |
| 18 | + | "used_space": used, | |
| 19 | + | "free_space": free, | |
| 20 | + | "usage_percent": usage_percent, | |
| 21 | + | } | |
| 22 | + | except Exception as e: | |
| 23 | + | return {"error": str(e)} | |
| 24 | + | ||
| 25 | + | @staticmethod | |
| 26 | + | def format_size(size_in_bytes): | |
| 27 | + | for unit in ["B", "KB", "MB", "GB", "TB"]: | |
| 28 | + | if size_in_bytes < 1024: | |
| 29 | + | return f"{size_in_bytes:.2f} {unit}" | |
| 30 | + | size_in_bytes /= 1024 | |
| 31 | + | return f"{size_in_bytes:.2f} PB" | |
| 32 | + | ||
| 33 | + | ||
| 34 | + | class DiskUsageHandler(BaseHTTPRequestHandler): | |
| 35 | + | def do_GET(self): | |
| 36 | + | parsed_path = urlparse(self.path) | |
| 37 | + | if parsed_path.path == "/disk-usage": | |
| 38 | + | # 取得 query string 中的 path 參數 | |
| 39 | + | query = parse_qs(parsed_path.query) | |
| 40 | + | path = query.get("path", ["/"])[0] | |
| 41 | + | ||
| 42 | + | # 執行 DiskUsage 並取得結果 | |
| 43 | + | disk_usage = DiskUsage(path) | |
| 44 | + | usage = disk_usage.get_usage() | |
| 45 | + | ||
| 46 | + | # 回傳 JSON 結果 | |
| 47 | + | self.send_response(200) | |
| 48 | + | self.send_header("Content-Type", "application/json") | |
| 49 | + | self.end_headers() | |
| 50 | + | self.wfile.write(json.dumps(usage).encode("utf-8")) | |
| 51 | + | else: | |
| 52 | + | self.send_response(404) | |
| 53 | + | self.send_header("Content-Type", "application/json") | |
| 54 | + | self.end_headers() | |
| 55 | + | self.wfile.write(json.dumps({"error": "Not Found"}).encode("utf-8")) | |
| 56 | + | ||
| 57 | + | ||
| 58 | + | def run(server_class=HTTPServer, handler_class=DiskUsageHandler, port=8000): | |
| 59 | + | server_address = ("", port) | |
| 60 | + | httpd = server_class(server_address, handler_class) | |
| 61 | + | print(f"Starting server on port {port}...") | |
| 62 | + | httpd.serve_forever() | |
| 63 | + | ||
| 64 | + | ||
| 65 | + | if __name__ == "__main__": | |
| 66 | + | run() | |
Plus récent
Plus ancien