Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

Django

最終更新 Markdown で表示Agent セットアップ

Django は Python Workers で利用できます。

Django アプリケーションは Web Server Gateway Interface(WSGI) または Asynchronous Server Gateway Interface(ASGI) と呼ばれるプロトコルを使います。

つまり、Django 自身はソケットの読み書きをしません。WSGI/ASGI アプリケーションは、uvicorn などの WSGI/ASGI サーバーに接続されることを前提とします。 WSGI/ASGI サーバーが、アプリケーションに代わって生のソケットをすべて扱います。

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"] 経由でアプリケーションに公開されます。

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"] 経由でアプリケーションに公開されます。

Django の設定

シークレットを渡す

Django の設定でシークレット(SECRET_KEY など)が必要なら、Worker シークレット から読めます。

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 の D1Durable Objects を Django のデータベースバックエンドとして使えます。 使うには django-cf パッケージをインストールします。

依存関係に django-cf を追加します。

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

データベースバックエンド

django-cf は、Cloudflare の D1 と Durable Objects を使う、SQLite 互換のバックエンドを 2 つ提供します。 どちらも同期の 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 バインディングを設定します。

{
  "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 の例を実行します。

役に立ちましたか?