-
Notifications
You must be signed in to change notification settings - Fork 67
Add flask hello world and todo app #89
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| # Flask Hello World | ||
|
|
||
| A minimal [Flask](https://flask.palletsprojects.com/) example app running on a | ||
| Python Worker via the WSGI adapter (`wsgi.fetch`). | ||
|
|
||
| ## How to Run | ||
|
|
||
| First ensure that `uv` is installed: | ||
| https://docs.astral.sh/uv/getting-started/installation/#standalone-installer | ||
|
|
||
| Now, if you run `uv run pywrangler dev` within this directory, it should use the config | ||
| in `wrangler.jsonc` to run the example. | ||
|
|
||
| You can also run `uv run pywrangler deploy` to deploy the example. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| { | ||
| "name": "flask-worker", | ||
| "version": "0.0.0", | ||
| "private": true, | ||
| "scripts": { | ||
| "deploy": "uv run pywrangler deploy", | ||
| "dev": "uv run pywrangler dev", | ||
| "start": "uv run pywrangler dev" | ||
| }, | ||
| "devDependencies": { | ||
| "wrangler": "^4.46.0" | ||
| }, | ||
| "dependencies": { | ||
| "workerd": "^1.20260505.1" | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| [project] | ||
| name = "flask-worker" | ||
| version = "0.1.0" | ||
| description = "Python flask example" | ||
| readme = "README.md" | ||
| requires-python = ">=3.12" | ||
| dependencies = [ | ||
| "webtypy>=0.1.7", | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We don't need webtypy here. |
||
| "flask", | ||
| # Local workers-runtime-sdk checkout (provides wsgi.py), built from source. | ||
| # pywrangler resolves the worker env from [project.dependencies] via | ||
| # `uv pip compile`, which ignores [tool.uv.sources] — so the local path must | ||
| # live directly in this string. Building a directory source requires the | ||
| # `[tool.pywrangler] allow-build` override below (turns off `--no-build`). | ||
| "workers-runtime-sdk @ file:///home/hood/Documents/programming/workers-py/packages/runtime-sdk", | ||
|
Comment on lines
+10
to
+15
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This should be removed |
||
| ] | ||
|
|
||
| [dependency-groups] | ||
| dev = [ | ||
| "workers-py", | ||
| ] | ||
|
|
||
| # Use the local workers-py (pywrangler) checkout so the `allow-build` override is | ||
| # available. This only affects the host dev tool, not the worker. | ||
| [tool.uv.sources] | ||
| workers-py = { path = "../../workers-py/packages/cli", editable = true } | ||
|
|
||
| [tool.pywrangler] | ||
| # Allow building sdists / local directory sources (drops `uv`'s `--no-build`), | ||
| # so the local workers-runtime-sdk directory above builds during sync. | ||
| allow-build = true | ||
|
Comment on lines
+23
to
+31
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. These too |
||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why twenty 😅 ? The last number was 17. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| import wsgi | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this should be |
||
| from flask import Flask, jsonify, request | ||
| from workers import WorkerEntrypoint | ||
|
|
||
|
|
||
| class Default(WorkerEntrypoint): | ||
| async def fetch(self, request): | ||
| return await wsgi.fetch(app, request, self.env) | ||
|
|
||
|
|
||
| app = Flask(__name__) | ||
|
|
||
|
|
||
| @app.get("/") | ||
| def root(): | ||
| return jsonify(message="ok") | ||
|
|
||
|
|
||
| @app.get("/hello/<name>") | ||
| def hello(name): | ||
| return jsonify(message=f"Hello, {name}!") | ||
|
|
||
|
|
||
| @app.post("/echo") | ||
| def echo(): | ||
| return jsonify(received=request.get_json(silent=True), args=request.args.to_dict()) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| { | ||
| "$schema": "node_modules/wrangler/config-schema.json", | ||
| "name": "flask-worker", | ||
| "main": "src/worker.py", | ||
| "compatibility_date": "2025-11-02", | ||
| "compatibility_flags": [ | ||
| "python_workers", | ||
| "python_process_pth_files" | ||
| ], | ||
|
Comment on lines
+5
to
+9
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe let's use newer compat dates |
||
| "vars": { | ||
| "MESSAGE": "My env var" | ||
| }, | ||
| "observability": { | ||
| "enabled": true | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| # Python environments | ||
| .venv/ | ||
| .venv-workers/ | ||
| __pycache__/ | ||
| *.py[cod] | ||
|
|
||
| # Vendored Pyodide wheels, re-created by `pywrangler dev`/`deploy` | ||
| python_modules/ | ||
|
|
||
| # Local Wrangler/miniflare state, including the local D1 database | ||
| .wrangler/ | ||
|
|
||
| node_modules/ | ||
| .dev.vars | ||
| .env |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| # Flask Notes | ||
|
|
||
| Example todo notes app with D1 as the database. | ||
|
|
||
| ## How it works | ||
|
|
||
| Uses the `workers.wsgi` adaptor to run flask and `src/d1.py` provides a | ||
| synchronous wrapper for d1. | ||
|
|
||
| ## Layout | ||
|
|
||
| ``` | ||
| migrations/0001_create_notes.sql D1 schema | ||
| public/ Static frontend (served from the edge) | ||
| src/entry.py Worker entrypoint (async → WSGI) | ||
| src/app.py Flask app: routes, validation, errors | ||
| src/d1.py Synchronous D1 wrapper | ||
| wrangler.jsonc Worker config, assets + D1 binding | ||
| ``` | ||
|
|
||
| ## Run locally | ||
|
|
||
| ```bash | ||
| uv sync | ||
| uv run pywrangler d1 migrations apply flask-notes --local | ||
| uv run pywrangler dev | ||
| ``` | ||
|
|
||
|
|
||
| ## Deploy | ||
|
|
||
| 1. Create the database and copy the id it prints: | ||
|
|
||
| ```bash | ||
| uv run pywrangler d1 create flask-notes | ||
| ``` | ||
|
|
||
| 2. Put that id in `wrangler.jsonc` under `d1_databases[0].database_id`, | ||
| replacing `REPLACE_WITH_YOUR_DATABASE_ID`. | ||
|
|
||
| 3. Apply the schema to the real database and deploy: | ||
|
|
||
| ```bash | ||
| uv run pywrangler d1 migrations apply flask-notes --remote | ||
| uv run pywrangler deploy | ||
| ``` |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| -- Migration number: 0001 create notes table | ||
|
|
||
| CREATE TABLE IF NOT EXISTS notes ( | ||
| id INTEGER PRIMARY KEY AUTOINCREMENT, | ||
| title TEXT NOT NULL, | ||
| body TEXT NOT NULL DEFAULT '', | ||
| done INTEGER NOT NULL DEFAULT 0 CHECK (done IN (0, 1)), | ||
| created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')), | ||
| updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')) | ||
| ); | ||
|
|
||
| -- The default listing is "newest first", and the UI filters on `done`. | ||
| CREATE INDEX IF NOT EXISTS idx_notes_done_created_at | ||
| ON notes (done, created_at DESC); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,206 @@ | ||
| const $ = (sel) => document.querySelector(sel); | ||
|
|
||
| const els = { | ||
| form: $("#create-form"), | ||
| title: $("#title"), | ||
| body: $("#body"), | ||
| list: $("#notes"), | ||
| status: $("#status"), | ||
| search: $("#search"), | ||
| clearDone: $("#clear-done"), | ||
| filters: document.querySelectorAll(".filter"), | ||
| template: $("#note-template"), | ||
| }; | ||
|
|
||
| let filter = "all"; | ||
| let search = ""; | ||
|
|
||
| /** Fetch wrapper that surfaces the API's JSON `error` field. */ | ||
| async function api(path, options = {}) { | ||
| const res = await fetch(path, { | ||
| headers: options.body ? { "Content-Type": "application/json" } : {}, | ||
| ...options, | ||
| }); | ||
| if (res.status === 204) return null; | ||
|
|
||
| const data = await res.json().catch(() => null); | ||
| if (!res.ok) { | ||
| throw new Error(data?.error ?? `Request failed (${res.status})`); | ||
| } | ||
| return data; | ||
| } | ||
|
|
||
| function setStatus(message, isError = false) { | ||
| els.status.textContent = message; | ||
| els.status.classList.toggle("status--error", isError); | ||
| } | ||
|
|
||
| function formatDate(iso) { | ||
| // Timestamps are stored as UTC without a timezone-aware parser on the server, | ||
| // so normalize to a real Date for locale-aware display. | ||
| const date = new Date(iso.endsWith("Z") ? iso : `${iso}Z`); | ||
| return Number.isNaN(date.valueOf()) ? iso : date.toLocaleString(); | ||
| } | ||
|
|
||
| function renderNote(note) { | ||
| const el = els.template.content.firstElementChild.cloneNode(true); | ||
| el.dataset.id = note.id; | ||
| el.classList.toggle("is-done", note.done); | ||
|
|
||
| const check = el.querySelector(".note__check"); | ||
| const title = el.querySelector(".note__title"); | ||
| const body = el.querySelector(".note__body"); | ||
|
|
||
| check.checked = note.done; | ||
| // textContent (not innerHTML) — note content is untrusted user input. | ||
| title.textContent = note.title; | ||
| body.textContent = note.body; | ||
| title.contentEditable = "plaintext-only"; | ||
| body.contentEditable = "plaintext-only"; | ||
| el.querySelector(".note__meta").textContent = `Updated ${formatDate(note.updated_at)}`; | ||
|
|
||
| check.addEventListener("change", () => patch(el, { done: check.checked })); | ||
|
|
||
| // Commit inline edits on blur, but only when the text actually changed. | ||
| const commit = (field, node, original) => { | ||
| const value = node.textContent.trim(); | ||
| if (value === original) return; | ||
| if (field === "title" && !value) { | ||
| node.textContent = original; // titles are required | ||
| return; | ||
| } | ||
| patch(el, { [field]: value }); | ||
| }; | ||
|
|
||
| for (const [field, node] of [["title", title], ["body", body]]) { | ||
| node.addEventListener("focus", () => { | ||
| node.dataset.original = node.textContent.trim(); | ||
| }); | ||
| node.addEventListener("blur", () => commit(field, node, node.dataset.original)); | ||
| node.addEventListener("keydown", (e) => { | ||
| if (e.key === "Enter" && !e.shiftKey) { | ||
| e.preventDefault(); | ||
| node.blur(); | ||
| } else if (e.key === "Escape") { | ||
| node.textContent = node.dataset.original; | ||
| node.blur(); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| el.querySelector(".note__delete").addEventListener("click", () => remove(el)); | ||
| return el; | ||
| } | ||
|
|
||
| function render(notes) { | ||
| els.list.replaceChildren(...notes.map(renderNote)); | ||
|
|
||
| if (notes.length === 0) { | ||
| const empty = document.createElement("li"); | ||
| empty.className = "empty"; | ||
| empty.textContent = search | ||
| ? `No notes match “${search}”.` | ||
| : filter === "done" | ||
| ? "Nothing completed yet." | ||
| : filter === "active" | ||
| ? "All done. Nice." | ||
| : "No notes yet — add one above."; | ||
| els.list.replaceChildren(empty); | ||
| } | ||
|
|
||
| const remaining = notes.filter((n) => !n.done).length; | ||
| setStatus( | ||
| notes.length === 0 | ||
| ? "" | ||
| : `${notes.length} note${notes.length === 1 ? "" : "s"} · ${remaining} active`, | ||
| ); | ||
| els.clearDone.hidden = !notes.some((n) => n.done); | ||
| } | ||
|
|
||
| async function load() { | ||
| const params = new URLSearchParams({ filter }); | ||
| if (search) params.set("q", search); | ||
| try { | ||
| const { notes } = await api(`/api/notes?${params}`); | ||
| render(notes); | ||
| } catch (err) { | ||
| setStatus(err.message, true); | ||
| } | ||
| } | ||
|
|
||
| async function patch(el, changes) { | ||
| el.classList.add("note--busy"); | ||
| try { | ||
| await api(`/api/notes/${el.dataset.id}`, { | ||
| method: "PATCH", | ||
| body: JSON.stringify(changes), | ||
| }); | ||
| await load(); | ||
| } catch (err) { | ||
| setStatus(err.message, true); | ||
| await load(); // resync so the UI never shows unsaved state | ||
| } | ||
| } | ||
|
|
||
| async function remove(el) { | ||
| el.classList.add("note--busy"); | ||
| try { | ||
| await api(`/api/notes/${el.dataset.id}`, { method: "DELETE" }); | ||
| await load(); | ||
| } catch (err) { | ||
| setStatus(err.message, true); | ||
| el.classList.remove("note--busy"); | ||
| } | ||
| } | ||
|
|
||
| els.form.addEventListener("submit", async (e) => { | ||
| e.preventDefault(); | ||
| const title = els.title.value.trim(); | ||
| if (!title) return; | ||
|
|
||
| const button = els.form.querySelector("button"); | ||
| button.disabled = true; | ||
| try { | ||
| await api("/api/notes", { | ||
| method: "POST", | ||
| body: JSON.stringify({ title, body: els.body.value.trim() }), | ||
| }); | ||
| els.form.reset(); | ||
| els.title.focus(); | ||
| await load(); | ||
| } catch (err) { | ||
| setStatus(err.message, true); | ||
| } finally { | ||
| button.disabled = false; | ||
| } | ||
| }); | ||
|
|
||
| for (const button of els.filters) { | ||
| button.addEventListener("click", () => { | ||
| filter = button.dataset.filter; | ||
| for (const b of els.filters) b.classList.toggle("is-active", b === button); | ||
| load(); | ||
| }); | ||
| } | ||
|
|
||
| // Debounce search so typing doesn't fire a request per keystroke. | ||
| let searchTimer; | ||
| els.search.addEventListener("input", () => { | ||
| clearTimeout(searchTimer); | ||
| searchTimer = setTimeout(() => { | ||
| search = els.search.value.trim(); | ||
| load(); | ||
| }, 200); | ||
| }); | ||
|
|
||
| els.clearDone.addEventListener("click", async () => { | ||
| if (!confirm("Delete all completed notes?")) return; | ||
| try { | ||
| await api("/api/notes/delete_completed", { method: "DELETE" }); | ||
| await load(); | ||
| } catch (err) { | ||
| setStatus(err.message, true); | ||
| } | ||
| }); | ||
|
|
||
| load(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's use newer versions since we bumped the minimal wrangler version in workers-py. I updated all the examples recently #67.