Flask ↗ 在 Python Workers 中受支持。
Flask 应用程序依赖称为 Web Server Gateway Interface (WSGI)的协议。这意味着 Flask 从不直接从 socket 读取或写入, 而是依赖 WSGI 服务器进行通信。
Python Workers 包含一个 WSGI 服务器 ↗, 你可以将其与 Flask 应用程序一起使用。
使用此快速入门运行一个最小的 Flask 应用程序。
-
使用你的 Flask 应用程序创建
src/worker.py:src/worker.pypython from flask import Flask from workers import wsgi app = Flask(__name__) @app.get("/") def index(): return {"message": "Hello from Flask"} Default = wsgi.entrypoint(app) -
在项目根目录创建
wrangler.jsonc:{ "$schema": "node_modules/wrangler/config-schema.json", "name": "my-flask-worker", "main": "src/worker.py", // Set this to today's date "compatibility_date": "2026-11-14", "compatibility_flags": ["python_workers"] }"$schema" = "node_modules/wrangler/config-schema.json" name = "my-flask-worker" main = "src/worker.py" # Set this to today's date compatibility_date = "2026-11-14" compatibility_flags = [ "python_workers" ] -
创建
pyproject.toml以声明依赖:pyproject.tomltoml [project] name = "flask-worker" version = "0.1.0" requires-python = ">=3.12" dependencies = [ "flask", ] [dependency-groups] dev = [ "workers-py", "workers-runtime-sdk", ] -
启动本地开发服务器:
uv run pywrangler dev -
在另一个终端向 Worker 发送请求:
curl http://localhost:8787/Worker 返回:
{"message":"Hello from Flask"}
你可以使用 Workers Static Assets 与 Flask 后端一起提供任何静态前端。 使用 Static Assets 意味着前端文件不会打包进 Worker 本身,从而保持包体积较小。
将静态文件放在例如 ./public/ 的目录中。然后在 Wrangler 文件中配置包含 binding 并将
run_worker_first 设为 true 的 assets 块。这确保每个请求先到达 Flask
Worker,因此 API 路由优先于静态文件。
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "my-flask-worker",
"main": "src/worker.py",
// Set this to today's date
"compatibility_date": "2026-11-14",
"compatibility_flags": ["python_workers"],
"assets": {
"directory": "./public/",
"binding": "ASSETS",
"run_worker_first": true
}
}"$schema" = "node_modules/wrangler/config-schema.json"
name = "my-flask-worker"
main = "src/worker.py"
# Set this to today's date
compatibility_date = "2026-11-14"
compatibility_flags = [ "python_workers" ]
[assets]
directory = "./public/"
binding = "ASSETS"
run_worker_first = true以下 Worker 先处理 API 路由,再转发其他请求。兜底处理程序会返回每个资源的正文、状态和标头:
from flask import Flask, Response, request
from pyodide.ffi import run_sync
from workers import wsgi
app = Flask(__name__)
@app.get("/api/hello")
def api_hello():
return {"message": "Hello from the API"}
@app.get("/")
@app.get("/<path:path>")
def frontend(path=""):
assets = request.environ["workers.env"].ASSETS
asset_response = run_sync(assets.fetch(f"https://assets.local/{path}"))
body = run_sync(asset_response.bytes())
return Response(
body,
status=asset_response.status,
headers=asset_response.headers,
)
Default = wsgi.entrypoint(app)run_sync 将两个异步资源操作桥接到 Flask 的同步
处理程序中。API 路由优先,未匹配的路径从
./public/ 提供。
克隆 cloudflare/python-workers-examples 仓库并运行其中的 flask-todo
示例:
git clone https://github.com/cloudflare/python-workers-examples
cd python-workers-examples/flask-todo
# See README.md for instructions