|
| 1 | +import uuid |
| 2 | + |
| 3 | +from flask import Flask, jsonify, request |
| 4 | +from flask_cors import CORS |
| 5 | +from pyodide.ffi import run_sync |
| 6 | +from werkzeug.exceptions import HTTPException |
| 7 | +from workers import WorkerEntrypoint, wsgi |
| 8 | + |
| 9 | +app = Flask(__name__) |
| 10 | +# Preserve the field order used below rather than sorting keys alphabetically. |
| 11 | +app.json.sort_keys = False |
| 12 | + |
| 13 | +# The todobackend.com spec runner calls this Worker from another origin. |
| 14 | +CORS(app, origins="*", send_wildcard=True, allow_headers="*", expose_headers="*") |
| 15 | + |
| 16 | + |
| 17 | +@app.errorhandler(HTTPException) |
| 18 | +def _json_error(err: HTTPException): |
| 19 | + """Render Werkzeug's HTTP errors as JSON instead of HTML.""" |
| 20 | + return jsonify({"detail": err.name}), err.code |
| 21 | + |
| 22 | + |
| 23 | +def _base_url() -> str: |
| 24 | + """Return the root URL for the todos collection.""" |
| 25 | + return request.url_root.rstrip("/") + "/todos" |
| 26 | + |
| 27 | + |
| 28 | +def _row_to_todo(row) -> dict: |
| 29 | + """Convert a D1 row into a todo dict with the absolute ``url`` field.""" |
| 30 | + return { |
| 31 | + "id": row.id, |
| 32 | + "title": row.title, |
| 33 | + "completed": bool(row.completed), |
| 34 | + "order": row.order, |
| 35 | + "url": f"{_base_url()}/{row.id}", |
| 36 | + } |
| 37 | + |
| 38 | + |
| 39 | +def _db(): |
| 40 | + """Get the D1 database binding from the WSGI environ.""" |
| 41 | + return request.environ["workers.env"].DB |
| 42 | + |
| 43 | + |
| 44 | +@app.get("/todos") |
| 45 | +def list_todos(): |
| 46 | + results = run_sync(_db().prepare("SELECT * FROM todos").all()) |
| 47 | + return jsonify([_row_to_todo(r) for r in results.results]) |
| 48 | + |
| 49 | + |
| 50 | +@app.post("/todos") |
| 51 | +def create_todo(): |
| 52 | + body = request.get_json(silent=True) or {} |
| 53 | + todo_id = str(uuid.uuid4()) |
| 54 | + title = body.get("title", "") |
| 55 | + completed = 1 if body.get("completed", False) else 0 |
| 56 | + order = body.get("order") |
| 57 | + |
| 58 | + run_sync( |
| 59 | + _db() |
| 60 | + .prepare( |
| 61 | + 'INSERT INTO todos (id, title, completed, "order") VALUES (?, ?, ?, ?)' |
| 62 | + ) |
| 63 | + .bind(todo_id, title, completed, order) |
| 64 | + .run() |
| 65 | + ) |
| 66 | + |
| 67 | + row = run_sync( |
| 68 | + _db().prepare("SELECT * FROM todos WHERE id = ?").bind(todo_id).first() |
| 69 | + ) |
| 70 | + |
| 71 | + return jsonify(_row_to_todo(row)) |
| 72 | + |
| 73 | + |
| 74 | +@app.delete("/todos") |
| 75 | +def delete_all_todos(): |
| 76 | + run_sync(_db().prepare("DELETE FROM todos").run()) |
| 77 | + return jsonify([]) |
| 78 | + |
| 79 | + |
| 80 | +@app.get("/todos/<todo_id>") |
| 81 | +def get_todo(todo_id: str): |
| 82 | + row = run_sync( |
| 83 | + _db().prepare("SELECT * FROM todos WHERE id = ?").bind(todo_id).first() |
| 84 | + ) |
| 85 | + if row is None: |
| 86 | + return jsonify({"error": "not found"}) |
| 87 | + return jsonify(_row_to_todo(row)) |
| 88 | + |
| 89 | + |
| 90 | +@app.patch("/todos/<todo_id>") |
| 91 | +def update_todo(todo_id: str): |
| 92 | + body = request.get_json(silent=True) or {} |
| 93 | + sets = [] |
| 94 | + values = [] |
| 95 | + if "title" in body: |
| 96 | + sets.append("title = ?") |
| 97 | + values.append(body["title"]) |
| 98 | + if "completed" in body: |
| 99 | + sets.append("completed = ?") |
| 100 | + values.append(1 if body["completed"] else 0) |
| 101 | + if "order" in body: |
| 102 | + sets.append('"order" = ?') |
| 103 | + values.append(body["order"]) |
| 104 | + |
| 105 | + if sets: |
| 106 | + values.append(todo_id) |
| 107 | + run_sync( |
| 108 | + _db() |
| 109 | + .prepare(f"UPDATE todos SET {', '.join(sets)} WHERE id = ?") |
| 110 | + .bind(*values) |
| 111 | + .run() |
| 112 | + ) |
| 113 | + |
| 114 | + row = run_sync( |
| 115 | + _db().prepare("SELECT * FROM todos WHERE id = ?").bind(todo_id).first() |
| 116 | + ) |
| 117 | + if row is None: |
| 118 | + return jsonify({"error": "not found"}) |
| 119 | + return jsonify(_row_to_todo(row)) |
| 120 | + |
| 121 | + |
| 122 | +@app.delete("/todos/<todo_id>") |
| 123 | +def delete_todo(todo_id: str): |
| 124 | + run_sync(_db().prepare("DELETE FROM todos WHERE id = ?").bind(todo_id).run()) |
| 125 | + return jsonify([]) |
| 126 | + |
| 127 | + |
| 128 | +Default = wsgi.entrypoint(app) |
0 commit comments