Base commune et stockage SQLite

Configuration par variables MC_*, heure de Paris sans zoneinfo,
JSON atomique, journal masquant les secrets, verrou, pause.
SQLite 14 jours, cle unique (source, station, dh_utc).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cette révision appartient à :
Théo GastineletClaude Opus 5.5 a révisé 2026-10-16 18:55:48 +02:00
révision 34c1bf6736
7 fichiers modifiés
+477

Aucun fichier ne correspond à votre recherche

+10
Voir le fichier
@@ -0,0 +1,10 @@
ref/
__pycache__/
*.pyc
.secrets/
*.sqlite
*.sqlite-*
var/
public/
*.token
*.key
+1
Voir le fichier
@@ -0,0 +1 @@
"""Collecteur du site météo public (weather.gastinel.me). Python 3, bibliothèque standard seulement."""
+236
Voir le fichier
@@ -0,0 +1,236 @@
"""Outils communs : configuration, heure de Paris, JSON atomique, journal, verrou, masquage des secrets.
Aucun chemin, nom de serveur ni secret n'est écrit en dur : tout vient de variables d'environnement
(voir `Config.depuis_env`) avec des valeurs par défaut relatives au dossier personnel.
"""
import datetime as dt
import json
import os
import re
import urllib.parse
from dataclasses import dataclass
from pathlib import Path
try: # fcntl n'existe que sous Unix (le VPS) ; les tests tournent aussi sous Windows
import fcntl
except ImportError: # pragma: no cover
fcntl = None
UTC = dt.timezone.utc
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
@dataclass
class Config:
base: Path # état, journal, base SQLite
public: Path # racine servie par Caddy (on écrit dans public/data/)
quota_commun: Path # compteur partagé avec le collecteur GWS et meteo-direct
jeton_infoclimat: Path # lu au moment de l'appel, jamais copié
cle_romma: Path
stations: Path # liste des stations Infoclimat suivies (JSON)
plafond_commun: int = 4999 # même plafond que le collecteur (décision du 29/09)
plafond_site: int = 1000 # plafond propre au site (décision du 16/10)
seuil_alerte: float = 0.80
alerte_active: bool = False # aucun envoi réel tant que Théo ne l'a pas activé
ntfy_url: str = ""
compte_par_station: bool = False # parade si Infoclimat compte une requête par station (§2.4)
lot_max: int = 25
garder_jours: int = 14
fiche_heures: int = 48
romma_actif: bool = True
infoclimat_actif: bool = True
direct_compat: Path = None # si défini : écrit aussi l'ancien direct.json (site LAN)
@classmethod
def depuis_env(cls, env=None):
e = os.environ if env is None else env
home = Path.home()
base = Path(e.get("MC_BASE") or home / "meteo-collecte")
def chemin(nom, defaut):
return Path(e[nom]) if e.get(nom) else defaut
def oui(nom, defaut):
v = e.get(nom)
return defaut if v is None else v.strip().lower() in ("1", "oui", "true", "yes")
return cls(
base=base,
public=chemin("MC_PUBLIC", base / "public"),
quota_commun=chemin("MC_QUOTA_COMMUN", home / "gws-collecte" / "quota.json"),
jeton_infoclimat=chemin("MC_JETON_INFOCLIMAT", home / "gws-collecte" / "infoclimat.token"),
cle_romma=chemin("MC_CLE_ROMMA", base / ".secrets" / "romma.key"),
stations=chemin("MC_STATIONS", Path(__file__).resolve().parent.parent / "config" / "stations.json"),
plafond_commun=int(e.get("MC_PLAFOND_COMMUN", 4999)),
plafond_site=int(e.get("MC_PLAFOND_SITE", 1000)),
alerte_active=oui("MC_ALERTE_ACTIVE", False),
ntfy_url=e.get("MC_NTFY_URL", ""),
compte_par_station=oui("MC_COMPTE_PAR_STATION", False),
lot_max=int(e.get("MC_LOT_MAX", 25)),
romma_actif=oui("MC_ROMMA_ACTIF", True),
infoclimat_actif=oui("MC_INFOCLIMAT_ACTIF", True),
direct_compat=chemin("MC_DIRECT_COMPAT", None),
)
# ---------------------------------------------------------------------------
# Heure de Paris (règle européenne codée ici : zoneinfo demande tzdata, absent sous Windows)
# ---------------------------------------------------------------------------
def _dernier_dimanche(annee, mois):
d = dt.date(annee, mois, 31)
return d - dt.timedelta(days=(d.weekday() + 1) % 7)
def decalage_paris(utc):
"""Décalage de Paris sur l'UTC à l'instant `utc` (aware) : 1 h (CET) ou 2 h (CEST)."""
a = utc.year
debut = dt.datetime.combine(_dernier_dimanche(a, 3), dt.time(1), UTC)
fin = dt.datetime.combine(_dernier_dimanche(a, 10), dt.time(1), UTC)
return dt.timedelta(hours=2 if debut <= utc < fin else 1)
def vers_paris(utc):
return (utc + decalage_paris(utc)).replace(tzinfo=None)
def paris_vers_utc(local, maintenant=None):
"""Heure locale de Paris (naïve) -> instant UTC.
None si l'heure n'existe pas (passage à l'heure d'été). Pour l'heure doublée d'octobre, on garde la plus
récente des deux qui n'est pas dans le futur par rapport à `maintenant` (sinon la plus ancienne).
"""
possibles = []
for h in (2, 1):
c = (local - dt.timedelta(hours=h)).replace(tzinfo=UTC)
if (c + decalage_paris(c)).replace(tzinfo=None) == local:
possibles.append(c)
if not possibles:
return None
if len(possibles) == 1 or maintenant is None:
return possibles[0]
passes = [c for c in possibles if c <= maintenant]
return max(passes) if passes else min(possibles)
def jour_paris(utc):
return str(vers_paris(utc).date())
def fmt_utc(t):
return t.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S")
def lire_utc(s):
return dt.datetime.strptime(s, "%Y-%m-%d %H:%M:%S").replace(tzinfo=UTC)
def iso(t):
return t.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
# ---------------------------------------------------------------------------
# Fichiers
# ---------------------------------------------------------------------------
def lire_json(p, defaut):
try:
return json.loads(Path(p).read_text(encoding="utf-8"))
except (OSError, ValueError):
return defaut
def ecrire_json(p, d, compact=True):
"""Écriture atomique : fichier temporaire dans le même dossier, puis os.replace."""
p = Path(p)
p.parent.mkdir(parents=True, exist_ok=True)
tmp = p.with_name(p.name + ".tmp-%d" % os.getpid())
texte = json.dumps(d, ensure_ascii=False, separators=(",", ":") if compact else None,
indent=None if compact else 1)
tmp.write_text(texte, encoding="utf-8")
os.replace(tmp, p)
def lire_secret(p):
"""Lit un jeton ou une clé au moment de l'appel. Le contenu n'est jamais journalisé."""
return Path(p).read_text(encoding="utf-8").strip()
def scrub(texte, *secrets):
"""Masque tout paramètre token=/apikey= d'URL et chaque secret, en clair ou encodé pour l'URL."""
texte = re.sub(r"(?i)\b(token|apikey)=[^&\s)\"']*", lambda m: m.group(1) + "=***", str(texte))
for s in secrets:
if s:
texte = texte.replace(s, "***")
enc = urllib.parse.quote(s, safe="")
if enc != s:
texte = texte.replace(enc, "***")
return texte
class Journal:
"""Journal texte horodaté (heure de Paris). Tout message passe par `scrub`."""
def __init__(self, fichier):
self.fichier = Path(fichier)
self.secrets = []
def masquer(self, *secrets):
self.secrets.extend(s for s in secrets if s)
def __call__(self, msg, maintenant=None):
t = maintenant or dt.datetime.now(UTC)
self.fichier.parent.mkdir(parents=True, exist_ok=True)
with open(self.fichier, "a", encoding="utf-8") as f:
f.write(vers_paris(t).strftime("%Y-%m-%d %H:%M:%S ") + scrub(msg, *self.secrets) + "\n")
class Verrou:
"""Verrou exclusif non bloquant (fcntl). Sans fcntl (Windows, tests), le verrou est toujours obtenu."""
def __init__(self, fichier):
self.fichier = Path(fichier)
self.f = None
def __enter__(self):
self.fichier.parent.mkdir(parents=True, exist_ok=True)
self.f = open(self.fichier, "w")
if fcntl is not None:
try:
fcntl.flock(self.f, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
self.f.close()
self.f = None
return False
return True
def __exit__(self, *a):
if self.f:
self.f.close()
class Pause:
"""Pause après erreur (fichier contenant un timestamp), reprise de direct.py : 15 min par défaut."""
def __init__(self, fichier, duree_s=15 * 60):
self.fichier = Path(fichier)
self.duree_s = duree_s
def active(self, maintenant):
try:
return float(self.fichier.read_text()) > maintenant.timestamp()
except (OSError, ValueError):
return False
def jusqua(self):
try:
return dt.datetime.fromtimestamp(float(self.fichier.read_text()), UTC)
except (OSError, ValueError):
return None
def poser(self, maintenant):
self.fichier.parent.mkdir(parents=True, exist_ok=True)
self.fichier.write_text(str(maintenant.timestamp() + self.duree_s))
+107
Voir le fichier
@@ -0,0 +1,107 @@
"""Stockage SQLite : 14 jours glissants, une ligne par (source, station, instant UTC).
Chaque ligne garde sa source. Aucune fusion ni moyenne entre sources : une même station physique publiée
par deux réseaux donne deux séries distinctes (source différente).
"""
import datetime as dt
import sqlite3
from .commun import UTC, fmt_utc
CHAMPS = ("temperature", "humidite", "point_de_rosee", "pression", "vent_moyen", "vent_rafales",
"vent_direction", "pluie_1h", "pluie_cumul", "rayonnement")
SCHEMA = """
CREATE TABLE IF NOT EXISTS mesures (
source TEXT NOT NULL,
station_id TEXT NOT NULL,
dh_utc TEXT NOT NULL, -- 'AAAA-MM-JJ HH:MM:SS', toujours UTC
%s,
recu_utc TEXT NOT NULL, -- première réception (sert à mesurer le délai de publication)
UNIQUE (source, station_id, dh_utc)
);
CREATE INDEX IF NOT EXISTS mesures_dh ON mesures (dh_utc);
CREATE TABLE IF NOT EXISTS stations (
source TEXT NOT NULL,
station_id TEXT NOT NULL,
nom TEXT, lat REAL, lon REAL, altitude REAL, licence TEXT, lien TEXT, extra TEXT,
PRIMARY KEY (source, station_id)
);
""" % ",\n ".join("%s REAL" % c for c in CHAMPS)
class Stockage:
def __init__(self, chemin):
self.db = sqlite3.connect(str(chemin), timeout=30)
self.db.row_factory = sqlite3.Row
self.db.executescript(SCHEMA)
self.db.commit()
def fermer(self):
self.db.close()
def ajouter(self, source, station_id, mesures, recu):
"""Insère des mesures {dh_utc, champs...}. Les doublons (même clé) sont ignorés, la première
réception est conservée. Renvoie le nombre de lignes nouvelles."""
n = 0
cols = ("source", "station_id", "dh_utc") + CHAMPS + ("recu_utc",)
sql = "INSERT OR IGNORE INTO mesures (%s) VALUES (%s)" % (",".join(cols), ",".join("?" * len(cols)))
for m in mesures:
vals = (source, str(station_id), m["dh_utc"]) + tuple(_num(m.get(c)) for c in CHAMPS) + (fmt_utc(recu),)
n += self.db.execute(sql, vals).rowcount
self.db.commit()
return n
def maj_station(self, source, station_id, **meta):
"""Met à jour les métadonnées d'une station (seuls les champs non vides remplacent l'existant)."""
champs = ("nom", "lat", "lon", "altitude", "licence", "lien", "extra")
meta = {k: v for k, v in meta.items() if k in champs and v not in (None, "")}
self.db.execute("INSERT OR IGNORE INTO stations (source, station_id) VALUES (?, ?)", (source, str(station_id)))
if meta:
self.db.execute("UPDATE stations SET %s WHERE source=? AND station_id=?" %
", ".join("%s=?" % k for k in meta), tuple(meta.values()) + (source, str(station_id)))
self.db.commit()
def stations(self):
return [dict(r) for r in self.db.execute("SELECT * FROM stations ORDER BY source, station_id")]
def derniere(self, source, station_id):
r = self.db.execute("SELECT * FROM mesures WHERE source=? AND station_id=? ORDER BY dh_utc DESC LIMIT 1",
(source, str(station_id))).fetchone()
return dict(r) if r else None
def serie(self, source, station_id, depuis):
return [dict(r) for r in self.db.execute(
"SELECT * FROM mesures WHERE source=? AND station_id=? AND dh_utc>=? ORDER BY dh_utc",
(source, str(station_id), fmt_utc(depuis)))]
def instants(self, source, station_id, n=30):
"""Les n derniers (dh_utc, recu_utc), du plus ancien au plus récent : sert à mesurer le pas réel."""
rows = self.db.execute("SELECT dh_utc, recu_utc FROM mesures WHERE source=? AND station_id=? "
"ORDER BY dh_utc DESC LIMIT ?", (source, str(station_id), n)).fetchall()
return [(r[0], r[1]) for r in reversed(rows)]
def purger(self, maintenant, jours=14):
limite = fmt_utc(maintenant - dt.timedelta(days=jours))
n = self.db.execute("DELETE FROM mesures WHERE dh_utc < ?", (limite,)).rowcount
self.db.commit()
return n
def compter(self, source=None):
if source:
return self.db.execute("SELECT COUNT(*) FROM mesures WHERE source=?", (source,)).fetchone()[0]
return self.db.execute("SELECT COUNT(*) FROM mesures").fetchone()[0]
def _num(v):
if v is None:
return None
if isinstance(v, (int, float)) and not isinstance(v, bool):
return float(v)
try:
s = str(v).strip().replace(",", ".")
if not s or s.upper() == "NULL":
return None
return float(s)
except ValueError:
return None
Voir le fichier
Seulement les espaces.
+66
Voir le fichier
@@ -0,0 +1,66 @@
import datetime as dt
import tempfile
import unittest
from pathlib import Path
from meteo_collecte.commun import (UTC, Config, Journal, ecrire_json, lire_json, paris_vers_utc, scrub,
vers_paris)
class TestHeureParis(unittest.TestCase):
def test_ete_moins_deux_heures(self):
self.assertEqual(paris_vers_utc(dt.datetime(2026, 10, 14, 23, 50)),
dt.datetime(2026, 10, 14, 21, 50, tzinfo=UTC))
def test_hiver_moins_une_heure(self):
self.assertEqual(paris_vers_utc(dt.datetime(2026, 12, 1, 12, 0)), dt.datetime(2026, 12, 1, 11, 0, tzinfo=UTC))
def test_heure_inexistante_de_mars(self):
self.assertIsNone(paris_vers_utc(dt.datetime(2026, 3, 29, 2, 30)))
def test_heure_doublee_d_octobre(self):
local = dt.datetime(2026, 10, 25, 2, 30)
# Avant la bascule (00:40 UTC), seule la première occurrence (00:30 UTC) est passée.
self.assertEqual(paris_vers_utc(local, dt.datetime(2026, 10, 25, 0, 40, tzinfo=UTC)),
dt.datetime(2026, 10, 25, 0, 30, tzinfo=UTC))
# Après (01:40 UTC), on prend la seconde.
self.assertEqual(paris_vers_utc(local, dt.datetime(2026, 10, 25, 1, 40, tzinfo=UTC)),
dt.datetime(2026, 10, 25, 1, 30, tzinfo=UTC))
def test_minuit_paris(self):
self.assertEqual(str(vers_paris(dt.datetime(2026, 10, 16, 22, 30, tzinfo=UTC)).date()), "2026-10-17")
class TestSecrets(unittest.TestCase):
def test_scrub(self):
m = "error for url (https://x/?a=1&token=AB%2BC&b=2): https://y/?apikey=K1 ; brut AB+C"
v = scrub(m, "AB+C")
self.assertNotIn("AB", v)
self.assertNotIn("K1", v)
self.assertIn("token=***&b=2", v)
def test_journal_masque(self):
with tempfile.TemporaryDirectory() as d:
j = Journal(Path(d) / "j.log")
j.masquer("SECRET123")
j("erreur SECRET123")
self.assertNotIn("SECRET123", (Path(d) / "j.log").read_text(encoding="utf-8"))
class TestFichiers(unittest.TestCase):
def test_ecriture_atomique(self):
with tempfile.TemporaryDirectory() as d:
p = Path(d) / "a" / "b.json"
ecrire_json(p, {"é": 1})
self.assertEqual(lire_json(p, None), {"é": 1})
self.assertEqual([x.name for x in p.parent.iterdir()], ["b.json"])
def test_config_sans_chemin_en_dur(self):
c = Config.depuis_env({"MC_BASE": "/tmp/x", "MC_PLAFOND_SITE": "800"})
self.assertEqual(c.plafond_site, 800)
self.assertEqual(c.public, Path("/tmp/x") / "public")
self.assertFalse(c.alerte_active)
if __name__ == "__main__":
unittest.main()
+57
Voir le fichier
@@ -0,0 +1,57 @@
import datetime as dt
import tempfile
import unittest
from pathlib import Path
from meteo_collecte.commun import UTC
from meteo_collecte.stockage import Stockage
T0 = dt.datetime(2026, 10, 16, 12, 0, tzinfo=UTC)
class TestStockage(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.s = Stockage(Path(self.tmp.name) / "m.sqlite")
def tearDown(self):
self.s.fermer()
self.tmp.cleanup()
def test_cle_unique_et_premiere_reception_gardee(self):
m = [{"dh_utc": "2026-10-16 11:50:00", "temperature": 5.1}]
self.assertEqual(self.s.ajouter("infoclimat", "000T0", m, T0), 1)
self.assertEqual(self.s.ajouter("infoclimat", "000T0", [{"dh_utc": "2026-10-16 11:50:00", "temperature": 9}],
T0 + dt.timedelta(minutes=10)), 0)
d = self.s.derniere("infoclimat", "000T0")
self.assertEqual(d["temperature"], 5.1)
self.assertEqual(d["recu_utc"], "2026-10-16 12:00:00")
def test_deux_sources_ne_se_melangent_pas(self):
self.s.ajouter("infoclimat", "80", [{"dh_utc": "2026-10-16 11:50:00", "temperature": 5.0}], T0)
self.s.ajouter("romma", "80", [{"dh_utc": "2026-10-16 11:50:00", "temperature": 7.0}], T0)
self.assertEqual(self.s.derniere("infoclimat", "80")["temperature"], 5.0)
self.assertEqual(self.s.derniere("romma", "80")["temperature"], 7.0)
self.assertEqual(self.s.compter(), 2)
def test_null_texte_et_virgule(self):
self.s.ajouter("romma", "1", [{"dh_utc": "2026-10-16 11:50:00", "temperature": "NULL",
"pression": "1012,5"}], T0)
d = self.s.derniere("romma", "1")
self.assertIsNone(d["temperature"])
self.assertEqual(d["pression"], 1012.5)
def test_purge_14_jours(self):
self.s.ajouter("romma", "1", [{"dh_utc": "2026-10-01 11:50:00"}, {"dh_utc": "2026-10-03 11:50:00"}], T0)
self.assertEqual(self.s.purger(T0, 14), 1)
self.assertEqual(self.s.compter(), 1)
def test_metadonnees_non_ecrasees_par_vide(self):
self.s.maj_station("romma", "1", nom="A", lat=45.0)
self.s.maj_station("romma", "1", nom="", lat=None, altitude=1000)
st = self.s.stations()[0]
self.assertEqual((st["nom"], st["lat"], st["altitude"]), ("A", 45.0, 1000))
if __name__ == "__main__":
unittest.main()