-
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
Open
hoodmane
wants to merge
4
commits into
cloudflare:main
Choose a base branch
from
hoodmane:flask-examples
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.114.0" | ||
| }, | ||
| "dependencies": { | ||
| "workerd": "^1.20260505.1" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| [project] | ||
| name = "flask-worker" | ||
| version = "0.1.0" | ||
| description = "Python flask example" | ||
| readme = "README.md" | ||
| requires-python = ">=3.12" | ||
| dependencies = [ | ||
| "flask", | ||
| ] | ||
|
|
||
| [dependency-groups] | ||
| dev = [ | ||
| "workers-py", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| from flask import Flask, jsonify, request | ||
| from workers import WorkerEntrypoint, wsgi | ||
|
|
||
|
|
||
| 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()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| { | ||
| "$schema": "node_modules/wrangler/config-schema.json", | ||
| "name": "flask-worker", | ||
| "main": "src/worker.py", | ||
| "compatibility_date": "2026-06-01", | ||
| "compatibility_flags": [ | ||
| "python_workers" | ||
| ], | ||
| "vars": { | ||
| "MESSAGE": "My env var" | ||
| }, | ||
| "observability": { | ||
| "enabled": true | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.