Repository navigation
Expand file tree
/
Copy pathweb_server.py
More file actions
77 lines (65 loc) · 2.3 KB
/
Copy pathweb_server.py
File metadata and controls
77 lines (65 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import json
import os
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlparse
import social_sim
ROOT = Path(__file__).resolve().parent
WEB_DIR = ROOT / "web"
class Handler(BaseHTTPRequestHandler):
def _send_json(self, payload, status=200):
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def _send_file(self, path: Path, content_type: str):
if not path.exists():
self._send_json({"error": "not found"}, 404)
return
data = path.read_bytes()
self.send_response(200)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
parsed = urlparse(self.path)
if parsed.path in ["/", "/index.html"]:
self._send_file(WEB_DIR / "index.html", "text/html; charset=utf-8")
return
if parsed.path == "/api/health":
self._send_json({"ok": True})
return
if parsed.path == "/api/simulate":
qs = parse_qs(parsed.query)
try:
rounds = int(qs.get("rounds", ["3"])[0])
except ValueError:
rounds = 3
rounds = max(1, min(rounds, 10))
try:
result = social_sim.simulate(rounds=rounds)
self._send_json(result)
except Exception as e:
self._send_json({"error": str(e)}, 500)
return
self._send_json({"error": "not found"}, 404)
if __name__ == "__main__":
port = 8000
if len(sys.argv) > 1:
try:
port = int(sys.argv[1])
except ValueError:
port = 8000
else:
try:
port = int(os.getenv("PORT", "8000"))
except ValueError:
port = 8000
HTTPServer.allow_reuse_address = True
server = HTTPServer(("0.0.0.0", port), Handler)
print(f"Server running at http://localhost:{port}")
server.serve_forever()