🐧 Ubuntu 24.04 `/opt/spideywords/server.py` (Port: 8081)
Kızınızın /opt/starwords servisi 8080 portunda çalışırken, oğlunuzun /opt/spideywords servisi hiçbir çakışma olmadan 8081 portunda çalışır.
/opt/spideywords/server.py içeriği:
📋 server.py Kopyala
#!/usr/bin/env python3
"""
SpideyWords Backend for Ubuntu 24.04 (/opt/spideywords)
Runs on Port 8081 alongside StarWords (Port 8080).
Syncs words.txt (/api/words) and missed.txt (/api/missed).
"""
import json
import os
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
PORT = int(os.environ.get("PORT", 8081))
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
WORDS_FILE = os.path.join(BASE_DIR, "words.txt")
MISSED_FILE = os.path.join(BASE_DIR, "missed.txt")
def atomic_write_txt(filepath, content):
tmp_path = filepath + ".tmp"
cleaned = content.strip()
with open(tmp_path, "w", encoding="utf-8") as f:
f.write((cleaned + "\n") if cleaned else "")
os.replace(tmp_path, filepath)
class SpideyWordsHandler(SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=BASE_DIR, **kwargs)
def _send_json(self, status_code, payload):
raw = json.dumps(payload, ensure_ascii=False).encode("utf-8")
self.send_response(status_code)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.send_header("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
self.send_header("Pragma", "no-cache")
self.end_headers()
self.wfile.write(raw)
def do_GET(self):
if self.path.startswith("/api/words"):
if not os.path.exists(WORDS_FILE):
open(WORDS_FILE, "w", encoding="utf-8").close()
with open(WORDS_FILE, "r", encoding="utf-8") as f:
content = f.read()
self._send_json(200, {"status": "ok", "content": content})
return
if self.path.startswith("/api/missed"):
if not os.path.exists(MISSED_FILE):
open(MISSED_FILE, "w", encoding="utf-8").close()
with open(MISSED_FILE, "r", encoding="utf-8") as f:
content = f.read()
self._send_json(200, {"status": "ok", "content": content})
return
return super().do_GET()
def do_POST(self):
if self.path.startswith("/api/words") or self.path.startswith("/api/missed"):
length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(length).decode("utf-8")
content = body
try:
data = json.loads(body)
if isinstance(data, dict) and "content" in data:
content = data["content"]
except json.JSONDecodeError:
pass
target = WORDS_FILE if self.path.startswith("/api/words") else MISSED_FILE
atomic_write_txt(target, content)
self._send_json(200, {"status": "ok", "content": content.strip()})
return
self._send_json(404, {"error": "Not found"})
if __name__ == "__main__":
print(f"SpideyWords Server running on http://0.0.0.0:{PORT}")
ThreadingHTTPServer(("0.0.0.0", PORT), SpideyWordsHandler).serve_forever()