File
Blob: samples/pyodide-fastapi/worker.py
| 1 | from asgi import env |
| 2 | from workers import WorkerEntrypoint |
| 3 | |
| 4 | |
| 5 | class Default(WorkerEntrypoint): |
| 6 | async def fetch(self, request, env): |
| 7 | import asgi |
| 8 | |
| 9 | return await asgi.fetch(app, request, env) |
| 10 | |
| 11 | |
| 12 | # Set up fastapi app |
| 13 | |
| 14 | from fastapi import FastAPI |
| 15 | from pydantic import BaseModel |
| 16 | |
| 17 | app = FastAPI() |
| 18 | |
| 19 | |
| 20 | @app.get("/hello") |
| 21 | async def hello(env=env): |
| 22 | return {"message": "Hello World", "secret": env.secret} |
| 23 | |
| 24 | |
| 25 | @app.get("/route") |
| 26 | async def route(): |
| 27 | return {"message": "this is my custom route"} |
| 28 | |
| 29 | |
| 30 | @app.get("/favicon.ico") |
| 31 | async def favicon(): |
| 32 | return {"message": "here's a favicon I guess?"} |
| 33 | |
| 34 | |
| 35 | @app.get("/items/{item_id}") |
| 36 | async def read_item(item_id: int): |
| 37 | return {"item_id": item_id} |
| 38 | |
| 39 | |
| 40 | class Item(BaseModel): |
| 41 | name: str |
| 42 | description: str | None = None |
| 43 | price: float |
| 44 | tax: float | None = None |
| 45 | |
| 46 | |
| 47 | @app.post("/items/") |
| 48 | async def create_item(item: Item): |
| 49 | return item |
| 50 | |
| 51 | |
| 52 | @app.put("/items/{item_id}") |
| 53 | async def create_item2(item_id: int, item: Item, q: str | None = None): |
| 54 | result = {"item_id": item_id, **item.model_dump()} |
| 55 | if q: |
| 56 | result.update({"q": q}) |
| 57 | return result |