Sauvegarde de la sélection sur le serveur (tri en plusieurs sessions)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Cette révision appartient à :
1 Parent
1e1771224f
révision
8c00e5adb5
5 fichiers modifiés
+59
-4
Aucun fichier ne correspond à votre recherche
@@ -0,0 +1,44 @@
|
||||
"""Serveur LAN du site Romma : fichiers statiques + sauvegarde de la selection (GET/POST /api/selection).
|
||||
Usage : python server.py [port] [dossier-du-site] (la selection est stockee dans selection.json a cote de ce script)"""
|
||||
import http.server, json, os, re, sys, threading, time
|
||||
|
||||
ICI = os.path.dirname(os.path.abspath(__file__))
|
||||
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8780
|
||||
SITE = os.path.abspath(sys.argv[2]) if len(sys.argv) > 2 else ICI
|
||||
FICHIER = os.path.join(ICI, 'selection.json')
|
||||
VERROU = threading.Lock()
|
||||
ID = re.compile(r'^[0-9A-Za-z_-]{1,12}$')
|
||||
|
||||
def lire():
|
||||
try:
|
||||
with open(FICHIER, encoding='utf-8') as f: return json.load(f)
|
||||
except Exception: return {'supprimees': None, 'maj': 0}
|
||||
|
||||
class H(http.server.SimpleHTTPRequestHandler):
|
||||
def __init__(self, *a, **k): super().__init__(*a, directory=SITE, **k)
|
||||
def _json(self, code, obj):
|
||||
b = json.dumps(obj).encode()
|
||||
self.send_response(code); self.send_header('Content-Type', 'application/json')
|
||||
self.send_header('Content-Length', str(len(b))); self.send_header('Cache-Control', 'no-store'); self.end_headers(); self.wfile.write(b)
|
||||
def do_GET(self):
|
||||
if self.path.split('?')[0] == '/api/selection':
|
||||
with VERROU: return self._json(200, lire())
|
||||
super().do_GET()
|
||||
def do_POST(self):
|
||||
if self.path.split('?')[0] != '/api/selection': return self._json(404, {'erreur': 'inconnu'})
|
||||
n = int(self.headers.get('Content-Length') or 0)
|
||||
if n <= 0 or n > 200000: return self._json(413, {'erreur': 'taille'})
|
||||
try:
|
||||
d = json.loads(self.rfile.read(n)); s = d['supprimees']
|
||||
if not isinstance(s, list) or len(s) > 5000 or not all(isinstance(x, str) and ID.match(x) for x in s): raise ValueError
|
||||
except Exception: return self._json(400, {'erreur': 'format'})
|
||||
obj = {'supprimees': sorted(set(s)), 'maj': int(time.time())}
|
||||
with VERROU:
|
||||
tmp = FICHIER + '.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as f: json.dump(obj, f)
|
||||
os.replace(tmp, FICHIER)
|
||||
self._json(200, obj)
|
||||
def log_message(self, *a): pass
|
||||
|
||||
if __name__ == '__main__':
|
||||
http.server.ThreadingHTTPServer(('0.0.0.0', PORT), H).serve_forever()
|
||||
Référencer dans un nouveau ticket
Bloquer un utilisateur