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

Django

最后更新 查看 MarkdownAgent 设置

Django ↗ 在 Python Workers 中受支持。

Django 应用程序使用称为 Web Server Gateway Interface (WSGI) ↗ 或 Asynchronous Server Gateway Interface (ASGI) ↗ 的协议。

这意味着 Django 本身从不从 socket 读取或写入。WSGI/ASGI 应用程序期望连接到 WSGI/ASGI 服务器,例如 uvicorn ↗。 WSGI/ASGI 服务器代表应用程序处理所有原始 socket。

Python Workers 为 WSGI 和 ASGI 都提供适配器, 因此你可以根据 Django 应用程序部署到 WSGI 还是 ASGI 进行选择。

快速入门

要在 Python Workers 中开始使用 Django,请按以下步骤操作:

  1. 使用 pywrangler init 创建 Django 项目:

    uv run pywrangler init django-worker --template https://github.com/cloudflare/python-workers-examples/tree/main/django
    cd django-worker
  2. 在本地运行 Worker:

    uv run pywrangler dev

在 ASGI 和 WSGI 之间选择

你的 Django 应用程序需要通过 ASGI 或 WSGI 提供服务。 虽然 Python Workers 针对 ASGI 进行了优化,你仍可以使用与 Django 兼容的 WSGI。

提供 WSGI 应用程序

使用 get_wsgi_application() 构建应用程序对象,并将其传给 workers.wsgi.fetch:

src/index.pypython
import os

from django.core.wsgi import get_wsgi_application
from workers import wsgi

# your Django settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")

app = get_wsgi_application()

Default = wsgi.entrypoint(app)

wsgi.fetch 接收应用程序对象、传入请求和环境。 它通过 scope["env"] 向应用程序公开绑定(binding)。

提供 ASGI 应用程序

使用 get_asgi_application() 构建应用程序对象,并将其传给 workers.asgi.fetch:

src/index.pypython
import os

from django.core.asgi import get_asgi_application
from workers import asgi

# your Django settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")

app = get_asgi_application()

Default = asgi.entrypoint(app)

asgi.fetch 接收应用程序对象、传入请求和环境。 它通过 scope["env"] 向应用程序公开绑定(binding)。

配置 Django 设置

传递密钥

如果你需要在 Django 设置中使用密钥(如 SECRET_KEY),可以从 Worker secret 读取:

src/app/settings.pypython
from workers import env

SECRET_KEY = env.DJANGO_SECRET_KEY

使用 uv run pywrangler secret put DJANGO_SECRET_KEY 创建密钥。

将 Cloudflare 存储用作 Django 后端

你可以将 Cloudflare D1 和 Durable Objects 用作 Django 数据库后端。 要使用它们,需要安装 django-cf ↗ 包。

将 django-cf 添加到依赖中:

[project]
dependencies = [
    "django",
    "django-cf",
]

数据库后端

django-cf 提供两个使用 Cloudflare D1 和 Durable Objects 的 SQLite 兼容后端。 两者都驱动同步 Django ORM,因此使用它们时请通过 WSGI 路径提供应用程序。

D1 后端

要将 D1 用作数据库后端,请先在 Wrangler 中设置 D1 数据库:

{
  "d1_databases": [
    {
      "binding": "DB",
      "database_name": "my-database",
      "database_id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    }
  ]
}
[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"

然后在 Django 设置中配置后端:

src/app/settings.pypython
DATABASES = {
    "default": {
        "ENGINE": "django_cf.db.backends.d1",
        # should match the binding name in your wrangler.jsonc
        "CLOUDFLARE_BINDING": "DB",
    }
}

这样就完成了。你的 Django 应用程序现在使用 D1 作为数据库后端。

src/index.pypython
import os

from django.core.wsgi import get_wsgi_application
from workers import WorkerEntrypoint, wsgi

# your Django settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")

application = get_wsgi_application()


class Default(WorkerEntrypoint):
    async def fetch(self, request):
        return await wsgi.fetch(application, request, self.env)

Durable Objects 后端

要将 Durable Objects 用作数据库后端,请先在 Wrangler 中设置 Durable Objects 绑定(binding):

{
  "durable_objects": {
    "bindings": [
      {
        "name": "DO_STORAGE",
        "class_name": "DjangoDurableObject"
      }
    ]
  },
  "migrations": [
    {
      "tag": "v1",
      "new_sqlite_classes": ["DjangoDurableObject"]
    }
  ]
}
[[durable_objects.bindings]]
name = "DO_STORAGE"
class_name = "DjangoDurableObject"

[[migrations]]
tag = "v1"
new_sqlite_classes = [ "DjangoDurableObject" ]

然后在 Django 设置中配置后端:

src/app/settings.pypython
DATABASES = {
    "default": {
        "ENGINE": "django_cf.db.backends.do",
    }
}

然后按如下方式更新 Python Worker:

src/index.pypython
import os

from django.core.wsgi import get_wsgi_application
from django_cf.db.backends.do.storage import set_storage
from workers import WorkerEntrypoint, DurableObject, wsgi

# your Django settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")

application = get_wsgi_application()


class DjangoDurableObject(DurableObject):
    def __init__(self, ctx, env):
        super().__init__(ctx, env)

        # Tell Django to use the Durable Object storage
        set_storage(self.ctx.storage.sql)

    async def fetch(self, request):
        return await wsgi.fetch(application, request, self.env)


class Default(WorkerEntrypoint):
    async def fetch(self, request):
        id = self.env.DO_STORAGE.idFromName("my-do-backend")
        stub = self.env.DO_STORAGE.get(id)
        return await stub.fetch(request)

更多示例

克隆 cloudflare/python-workers-examples 仓库并运行 Django 示例:

这篇文档对您有帮助吗?