Spaces:
Sleeping
Sleeping
File size: 2,343 Bytes
02ebf53 d2a98c6 02ebf53 d2a98c6 e9e401c 02ebf53 d2a98c6 02ebf53 e9e401c 02ebf53 7b108b2 d2a98c6 02ebf53 d2a98c6 02ebf53 d2a98c6 7b108b2 02ebf53 d2a98c6 02ebf53 d2a98c6 02ebf53 d2a98c6 02ebf53 d2a98c6 02ebf53 7b108b2 d2a98c6 7b108b2 d2a98c6 c175e0c d2a98c6 7b108b2 d2a98c6 e9e401c 02ebf53 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# app.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel # <--- Import BaseModel
import sqlite3
import os
# Define the Pydantic model for Item creation/update
class Item(BaseModel):
name: str
description: str | None = None # Use Union type hint for None
app = FastAPI()
# ... rest of your existing code ...
@app.post("/items/")
async def create_item(item: Item): # <--- Change parameter to 'item: Item'
conn = get_db_connection()
cursor = conn.cursor()
try:
query = "INSERT INTO items (name, description) VALUES (?, ?)"
cursor.execute(query, (item.name, item.description)) # Access attributes using item.name, item.description
conn.commit()
return {"message": "Item created successfully", "id": cursor.lastrowid}
except Exception as e:
conn.rollback()
raise HTTPException(status_code=500, detail=f"Error creating item: {e}")
finally:
cursor.close()
conn.close()
# ... Also update your @app.put("/items/{item_id}") endpoint similarly ...
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item): # <--- Change parameter to 'item: Item'
conn = get_db_connection()
cursor = conn.cursor()
try:
updates = []
params = []
if item.name is not None: # Access using item.name
updates.append("name = ?")
params.append(item.name)
if item.description is not None: # Access using item.description
updates.append("description = ?")
params.append(item.description)
if not updates:
raise HTTPException(status_code=400, detail="No fields to update provided")
query = f"UPDATE items SET {', '.join(updates)} WHERE id = ?"
params.append(item_id)
cursor.execute(query, tuple(params))
conn.commit()
if cursor.rowcount == 0:
raise HTTPException(status_code=404, detail="Item not found")
return {"message": "Item updated successfully"}
except HTTPException: # Re-raise if it's already an HTTPException
raise
except Exception as e:
conn.rollback()
raise HTTPException(status_code=500, detail=f"Error updating item: {e}")
finally:
cursor.close()
conn.close()
# ... rest of your existing code ... |