Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Cloudflare Docs
Log in

The FastAPI package is supported in Python Workers.

FastAPI applications use a protocol called theAsynchronous Server Gateway Interface (ASGI). This means that FastAPI never reads from or writes to a socket itself. An ASGI application expects to be hooked up to an ASGI server, typicallyuvicorn. The ASGI server handles all of the raw sockets on the application’s behalf.

The Workers runtime providesan ASGI server directly to your Python Worker, which lets you use FastAPI in Python Workers.

Get Started

Clone thecloudflare/python-workers-examples repository and run the FastAPI example:

Terminal window
gitclonehttps://github.com/cloudflare/python-workers-examples
cdpython-workers-examples/03-fastapi
uvrunpywranglerdev

Example code

Python
from workersimport WorkerEntrypoint
from fastapiimport FastAPI, Request
from pydanticimport BaseModel
import asgi
classDefault(WorkerEntrypoint):
asyncdeffetch(self,request):
returnawait asgi.fetch(app, request,self.env)
app=FastAPI()
@app.get("/")
asyncdefroot():
return{"message":"Hello, World!"}
@app.get("/env")
asyncdefroot(req: Request):
env= req.scope["env"]
return{"message":"Here is an example of getting an environment variable: "+ env.MESSAGE}
classItem(BaseModel):
name:str
description:str|None=None
price:float
tax:float|None=None
@app.post("/items/")
asyncdefcreate_item(item: Item):
return item
@app.put("/items/{item_id}")
asyncdefcreate_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}")
asyncdefread_item(item_id:int):
return{"item_id": item_id}

[8]ページ先頭

©2009-2025 Movatter.jp