askrobots / dbbasic-web
Public
A Unix-style Python web framework: filesystem routing, flat files, messages and cron, with CGI's simplicity at modern speed.
Dan Quellhorst
Replace multipart parser with stdlib-only implementation
eb957a2
9 months, 2 weeks ago
History
storage.py · 1.3 KB · 52 lines
| 1 | """Flat-file storage helpers""" |
| 2 | from pathlib import Path |
| 3 | from .settings import DATA_DIR |
| 4 | |
| 5 | |
| 6 | def data_path(*parts: str) -> Path: |
| 7 | """Get a safe path within the data directory""" |
| 8 | p = DATA_DIR.joinpath(*parts).resolve() |
| 9 | if not str(p).startswith(str(DATA_DIR)): |
| 10 | raise ValueError("Invalid path: attempted directory traversal") |
| 11 | p.parent.mkdir(parents=True, exist_ok=True) |
| 12 | return p |
| 13 | |
| 14 | |
| 15 | def write_text(rel: str, text: str) -> str: |
| 16 | """Write text to a flat file""" |
| 17 | p = data_path(rel) |
| 18 | p.write_text(text, encoding="utf-8") |
| 19 | return str(p) |
| 20 | |
| 21 | |
| 22 | def read_text(rel: str) -> str: |
| 23 | """Read text from a flat file""" |
| 24 | p = data_path(rel) |
| 25 | return p.read_text(encoding="utf-8") if p.exists() else "" |
| 26 | |
| 27 | |
| 28 | def write_bytes(rel: str, data: bytes) -> str: |
| 29 | """Write bytes to a flat file""" |
| 30 | p = data_path(rel) |
| 31 | p.write_bytes(data) |
| 32 | return str(p) |
| 33 | |
| 34 | |
| 35 | def read_bytes(rel: str) -> bytes: |
| 36 | """Read bytes from a flat file""" |
| 37 | p = data_path(rel) |
| 38 | return p.read_bytes() if p.exists() else b"" |
| 39 | |
| 40 | |
| 41 | def exists(rel: str) -> bool: |
| 42 | """Check if a flat file exists""" |
| 43 | return data_path(rel).exists() |
| 44 | |
| 45 | |
| 46 | def delete(rel: str) -> bool: |
| 47 | """Delete a flat file""" |
| 48 | p = data_path(rel) |
| 49 | if p.exists(): |
| 50 | p.unlink() |
| 51 | return True |
| 52 | return False |