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
jobs.py · 1.3 KB · 45 lines
| 1 | """Background jobs using dbbasic-queue (TSV-based, no Redis/Celery needed)""" |
| 2 | from dbbasic.queue import Queue |
| 3 | from .settings import DATA_DIR |
| 4 | |
| 5 | # Job queue stored in flat TSV files |
| 6 | job_queue = Queue(str(DATA_DIR / "jobs.tsv")) |
| 7 | |
| 8 | |
| 9 | def enqueue(task_name: str, **kwargs) -> str: |
| 10 | """Enqueue a background job""" |
| 11 | return job_queue.push({"task": task_name, "args": kwargs}) |
| 12 | |
| 13 | |
| 14 | def process_jobs(): |
| 15 | """Process pending jobs (run this in a worker process)""" |
| 16 | while True: |
| 17 | job = job_queue.pop() |
| 18 | if not job: |
| 19 | break |
| 20 | |
| 21 | task_name = job.get("task") |
| 22 | args = job.get("args", {}) |
| 23 | |
| 24 | # Dispatch to handlers |
| 25 | if task_name == "write_flatfile": |
| 26 | _write_flatfile(**args) |
| 27 | elif task_name == "process_upload": |
| 28 | _process_upload(**args) |
| 29 | else: |
| 30 | print(f"Unknown task: {task_name}") |
| 31 | |
| 32 | |
| 33 | def _write_flatfile(relpath: str, content: str) -> str: |
| 34 | """Write content to a flat file""" |
| 35 | from .storage import write_text |
| 36 | |
| 37 | return write_text(relpath, content) |
| 38 | |
| 39 | |
| 40 | def _process_upload(filename: str, data: bytes) -> dict: |
| 41 | """Process an uploaded file""" |
| 42 | from .storage import write_bytes |
| 43 | |
| 44 | path = write_bytes(f"uploads/{filename}", data) |
| 45 | return {"status": "processed", "path": path, "size": len(data)} |