A Unix-style Python web framework: filesystem routing, flat files, messages and cron, with CGI's simplicity at modern speed.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-web.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-web.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-web.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

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"""
2from pathlib import Path
3from .settings import DATA_DIR
4
5
6def 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
15def 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
22def 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
28def 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
35def 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
41def exists(rel: str) -> bool:
42 """Check if a flat file exists"""
43 return data_path(rel).exists()
44
45
46def 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