Open9

Cloudflare Workers Python

zztkmzztkm

とりあえず wrangler のバージョンはあげておいた方が良さそう

sudo npm install -g wrangler
zztkmzztkm

hello world

Type hint がないので、めちゃくちゃ体験が悪いがちゃんと動いて感動した。

from js import Response


async def on_fetch(request, env):
    return Response.new("Hello, World!!!!!!")
zztkmzztkm

FastAPI で kv を使うサンプル

import json
from fastapi import FastAPI, Response
from pydantic import BaseModel


app = FastAPI()

# env にアクセスするためのグローバル変数
# 他にやり方が思いつかなかった...
appenv = None


class Item(BaseModel):
    name: str
    bio: str


# お約束
async def on_fetch(request, env):
    import asgi
    global appenv
    appenv = env
    return await asgi.fetch(app, request, env)


@app.get("/")
async def index():
    return {"message": "Hello, World!"}


@app.get("/hello/{name}")
async def hello(name: str):
    item_json_str = await appenv.python_binding_test.get(name)
    if item_json_str is None:
        return Response(status_code=404)

    item_dict = json.loads(item_json_str)
    # バリデーション
    return Item(**item_dict)

@app.post("/hello")
async def hello(item: Item):
    await appenv.python_binding_test.put(item.name, item.model_dump_json())
    return Response(status_code=201)
zztkmzztkm

FastAPI に依存する workers のデプロイ

2024/4/3 現在、requirements.txt が必要な workers はまだサポートされてないっぽい(Discord の python-workers チャンネルでも言われてた)

❯ wrangler deploy
 ⛅️ wrangler 3.44.0
-------------------
▲ [WARNING] The entrypoint src/main.py defines a Python worker, support for Python workers is currently experimental.


Attaching additional modules:
┌─────────┬────────────────────┬──────┐
│ Name    │ Type               │ Size │
├─────────┼────────────────────┼──────┤
│ fastapi │ python-requirement │      │
└─────────┴────────────────────┴──────┘
Total Upload: 0.83 KiB / gzip: 0.45 KiB

✘ [ERROR] A request to the Cloudflare API failed.

  You cannot yet deploy Python Workers that depend on packages defined in requirements.txt. Support
  for Python packages is coming soon. [code: 10021]

  If you think this is a bug, please open an issue at:
  https://github.com/cloudflare/workers-sdk/issues/new/choose