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 à :
Théo GastineletClaude Sonnet 5.5 a révisé 2026-10-10 20:54:05 +02:00
1 Parent 1e1771224f
révision 8c00e5adb5
5 fichiers modifiés
+59 -4

Aucun fichier ne correspond à votre recherche

+2
Voir le fichier
@@ -1,2 +1,4 @@
*.avant-*
__pycache__/
selection.json
selection.json.tmp
+10 -1
Voir le fichier
@@ -5,7 +5,11 @@ var KEY='romma-simple-v4';
var supprimees={}, historique=[];
try{ supprimees=JSON.parse(localStorage.getItem(KEY)||'null'); }catch(e){ supprimees=null; }
if(!supprimees){ supprimees={}; ST.forEach(function(s){ if(s.statut.indexOf('doublon')===0) supprimees[s.id_romma]=1; }); }
function save(){ try{ localStorage.setItem(KEY,JSON.stringify(supprimees)); }catch(e){} }
function save(){
try{ localStorage.setItem(KEY,JSON.stringify(supprimees)); }catch(e){}
try{ fetch('/api/selection',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({supprimees:Object.keys(supprimees)})}).then(function(r){ majEtat(r.ok); },function(){ majEtat(false); }); }catch(e){ majEtat(false); }
}
function majEtat(ok){ var e=document.getElementById('etat'); if(e){ e.textContent=ok?'Enregistré sur le serveur':'Non enregistré (serveur injoignable)'; e.style.color=ok?'#1f7a45':'#b3261e'; } }
function esc(t){ return String(t==null?'':t).replace(/[&<>"']/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];}); }
var vueElim=false;
@@ -71,4 +75,9 @@ document.getElementById('b-copie').onclick=function(){
var pts=ST.filter(function(s){return s.lat!=null;}).map(function(s){return [s.lat,s.lon];});
if(pts.length) carte.fitBounds(pts,{padding:[20,20]});
rafraichir();
// reprise de la selection enregistree sur le serveur (plusieurs sessions possibles)
try{ fetch('/api/selection',{cache:'no-store'}).then(function(r){ return r.json(); }).then(function(d){
if(d&&Array.isArray(d.supprimees)){ supprimees={}; d.supprimees.forEach(function(id){ supprimees[id]=1; }); try{ localStorage.setItem(KEY,JSON.stringify(supprimees)); }catch(e){} rafraichir(); majEtat(true); }
else { save(); }
}).catch(function(){ majEtat(false); }); }catch(e){}
})();
+1
Voir le fichier
@@ -12,6 +12,7 @@
<header>
<h1>Stations Romma</h1>
<span id="compteur"></span>
<span id="etat" class="aide"></span>
<span class="aide">Clique sur une station (carte ou liste) pour la supprimer.</span>
<span class="actions">
<button id="b-annuler">Annuler</button>
+2 -3
Voir le fichier
@@ -1,4 +1,3 @@
@echo off
cd /d "%~dp0"
echo Site sur http://localhost:8780 et http://<IP-du-PC>:8780
python -m http.server 8780 --bind 0.0.0.0
start /min python server.py 8780 .
start /min python server.py 8781 ..\stations-romma-publie
+44
Voir le fichier
@@ -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()