跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

Flask

最后更新 查看 MarkdownAgent 设置

Flask ↗ 在 Python Workers 中受支持。

Flask 应用程序依赖称为 Web Server Gateway Interface (WSGI)的协议。这意味着 Flask 从不直接从 socket 读取或写入, 而是依赖 WSGI 服务器进行通信。

Python Workers 包含一个 WSGI 服务器 ↗, 你可以将其与 Flask 应用程序一起使用。

创建 Flask Worker

使用此快速入门运行一个最小的 Flask 应用程序。

  1. 使用你的 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)
  2. 在项目根目录创建 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" ]
  3. 创建 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",
    ]
  4. 启动本地开发服务器:

    uv run pywrangler dev
  5. 在另一个终端向 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 路由,再转发其他请求。兜底处理程序会返回每个资源的正文、状态和标头:

src/worker.pypython
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

这篇文档对您有帮助吗?