FastAPI
FastAPIパッケージはPython Workersでサポートされています。
FastAPIアプリケーションは、非同期サーバーゲートウェイインターフェース(ASGI) ↗というプロトコルを使用します。これは、FastAPIがソケットから読み取ったり、ソケットに書き込んだりしないことを意味します。ASGIアプリケーションは、通常uvicorn ↗というASGIサーバーに接続されることを期待します。ASGIサーバーは、アプリケーションの代理としてすべての生ソケットを処理します。
Workersランタイムは、Python Workerに直接ASGIサーバー ↗を提供し、これによりPython WorkersでFastAPIを使用できます。
cloudflare/python-workers-examplesリポジトリをクローンし、FastAPIの例を実行します:
git clone https://github.com/cloudflare/python-workers-examplescd python-workers-examples/03-fastapinpx wrangler@latest devfrom fastapi import FastAPI, Requestfrom pydantic import BaseModel
async def on_fetch(request, env): import asgi
return await asgi.fetch(app, request, env)
app = FastAPI()
@app.get("/")async def root(): return {"message": "こんにちは、世界!"}
@app.get("/env")async def root(req: Request): env = req.scope["env"] return {"message": "環境変数を取得する例です: " + env.MESSAGE}
class Item(BaseModel): name: str description: str | None = None price: float tax: float | None = None
@app.post("/items/")async def create_item(item: Item): return item
@app.put("/items/{item_id}")async def create_item(item_id: int, item: Item, q: str | None = None): result = {"item_id": item_id, **item.dict()} if q: result.update({"q": q}) return result
@app.get("/items/{item_id}")async def read_item(item_id: int): return {"item_id": item_id}