Spaces:
Runtime error
Runtime error
Download app.py from Pujan-Dev/testing_fastapi_with_mongodb: direct link, hf CLI and curl.
- Browser
- Download file 1.23 kB
-
https://huggingface.co/spaces/Pujan-Dev/testing_fastapi_with_mongodb/resolve/main/app.py
- Command line
-
hf download hf://spaces/Pujan-Dev/testing_fastapi_with_mongodb/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Pujan-Dev/testing_fastapi_with_mongodb/resolve/main/app.py
1.23 kB
| from fastapi import FastAPI, HTTPException | |
| from pydantic import BaseModel | |
| from db import db # assumes db is an instance of AsyncIOMotorDatabase | |
| from bson import ObjectId | |
| from bson.errors import InvalidId | |
| app = FastAPI() | |
| class Item(BaseModel): | |
| name: str | |
| description: str | |
| async def create_item(item: Item): | |
| result = await db["items"].insert_one(item.dict()) | |
| return {"id": str(result.inserted_id), "message": "Item created"} | |
| async def read_items(): | |
| items = [] | |
| cursor = db["items"].find() # This returns an AsyncIOMotorCursor | |
| async for document in cursor: | |
| document["id"] = str(document["_id"]) | |
| del document["_id"] | |
| items.append(document) | |
| return items | |
| def index(): | |
| return {"message": "Hello World"} | |
| async def read_item(item_id: str): | |
| try: | |
| oid = ObjectId(item_id) | |
| except InvalidId: | |
| raise HTTPException(status_code=400, detail="Invalid item ID format") | |
| item = await db["items"].find_one({"_id": oid}) | |
| if not item: | |
| raise HTTPException(status_code=404, detail="Item not found") | |
| item["id"] = str(item["_id"]) | |
| del item["_id"] | |
| return item | |