Download backend/store.py from m4az19/saef-api: direct link, hf CLI and curl.
- Browser
- Download file 1.99 kB
-
https://huggingface.co/spaces/m4az19/saef-api/resolve/main/backend/store.py
- Command line
-
hf download hf://spaces/m4az19/saef-api/backend/store.py
-
curl -L -o store.py https://huggingface.co/spaces/m4az19/saef-api/resolve/main/backend/store.py
1.99 kB
| """Small durable JSON document store; all paths are generated server-side.""" | |
| import json | |
| import os | |
| import sqlite3 | |
| import uuid | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parents[1] | |
| DATA = Path(os.environ.get('SATFORGE_DATA', ROOT / 'data' / 'runtime')) | |
| DATA.mkdir(parents=True, exist_ok=True) | |
| FILES = DATA / 'files' | |
| FILES.mkdir(exist_ok=True) | |
| def now(): | |
| return datetime.now(timezone.utc).isoformat() | |
| def connection(): | |
| con = sqlite3.connect(DATA / 'mission.sqlite', timeout=30) | |
| con.execute('CREATE TABLE IF NOT EXISTS records (kind TEXT, id TEXT, body TEXT, PRIMARY KEY(kind,id))') | |
| return con | |
| def put(kind, body, id=None): | |
| id = id or uuid.uuid4().hex | |
| body = {**body, 'id': id} | |
| with connection() as con: | |
| con.execute('INSERT OR REPLACE INTO records VALUES (?,?,?)', (kind, id, json.dumps(body, allow_nan=False))) | |
| return body | |
| def get(kind, id): | |
| with connection() as con: | |
| row = con.execute('SELECT body FROM records WHERE kind=? AND id=?', (kind, id)).fetchone() | |
| if row is None: | |
| raise KeyError(f'{kind} not found') | |
| return json.loads(row[0]) | |
| def all_records(kind): | |
| with connection() as con: | |
| rows = con.execute('SELECT body FROM records WHERE kind=? ORDER BY rowid DESC', (kind,)).fetchall() | |
| return [json.loads(row[0]) for row in rows] | |
| def event(message, provenance='SYSTEM', **details): | |
| return put('events', {'time': now(), 'message': message, 'provenance': provenance, **details}) | |
| def path_for(id, suffix): | |
| if not id.isalnum() or not suffix.replace('.', '').replace('_','').isalnum(): | |
| raise ValueError('Invalid asset identifier') | |
| return FILES / f'{id}.{suffix}' | |
| def asset(kind, name, source, **extra): | |
| return put('assets', {'kind':kind, 'name':name, 'source':source, 'retrieved_at':now(), | |
| 'acquisition_time':None, 'publication_time':None, 'license':'User must verify', | |
| 'processing':[], 'warnings':[], **extra}) | |