Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,59 +1,26 @@
|
|
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI, HTTPException
|
|
|
|
| 2 |
import sqlite3
|
| 3 |
import os
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
# Files in /app are generally persisted across restarts within a Space.
|
| 10 |
-
DATABASE_FILE = os.path.join(os.getcwd(), "data.db")
|
| 11 |
-
|
| 12 |
-
def get_db_connection():
|
| 13 |
-
try:
|
| 14 |
-
conn = sqlite3.connect(DATABASE_FILE)
|
| 15 |
-
# Configure connection to return rows as dictionaries for easier access
|
| 16 |
-
conn.row_factory = sqlite3.Row
|
| 17 |
-
return conn
|
| 18 |
-
except sqlite3.Error as err:
|
| 19 |
-
print(f"Error connecting to database: {err}")
|
| 20 |
-
raise HTTPException(status_code=500, detail="Database connection error")
|
| 21 |
|
| 22 |
-
|
| 23 |
-
async def startup_event():
|
| 24 |
-
# Create tables if they don't exist
|
| 25 |
-
conn = None # Initialize conn to None
|
| 26 |
-
try:
|
| 27 |
-
conn = get_db_connection()
|
| 28 |
-
cursor = conn.cursor()
|
| 29 |
-
cursor.execute("""
|
| 30 |
-
CREATE TABLE IF NOT EXISTS items (
|
| 31 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 32 |
-
name TEXT NOT NULL,
|
| 33 |
-
description TEXT
|
| 34 |
-
)
|
| 35 |
-
""")
|
| 36 |
-
conn.commit()
|
| 37 |
-
print(f"Database table 'items' checked/created successfully at {DATABASE_FILE}.")
|
| 38 |
-
except Exception as e:
|
| 39 |
-
print(f"Error during database startup: {e}")
|
| 40 |
-
# In a real app, you might want to handle this more gracefully,
|
| 41 |
-
# e.g., log the error and potentially shut down if essential tables can't be created.
|
| 42 |
-
finally:
|
| 43 |
-
if conn:
|
| 44 |
-
conn.close()
|
| 45 |
|
| 46 |
-
|
| 47 |
-
async def root():
|
| 48 |
-
return {"message": "Welcome to the API!"}
|
| 49 |
|
| 50 |
@app.post("/items/")
|
| 51 |
-
async def create_item(
|
| 52 |
conn = get_db_connection()
|
| 53 |
cursor = conn.cursor()
|
| 54 |
try:
|
| 55 |
query = "INSERT INTO items (name, description) VALUES (?, ?)"
|
| 56 |
-
cursor.execute(query, (name, description))
|
| 57 |
conn.commit()
|
| 58 |
return {"message": "Item created successfully", "id": cursor.lastrowid}
|
| 59 |
except Exception as e:
|
|
@@ -63,50 +30,21 @@ async def create_item(name: str, description: str = None):
|
|
| 63 |
cursor.close()
|
| 64 |
conn.close()
|
| 65 |
|
| 66 |
-
@app.
|
| 67 |
-
async def read_items():
|
| 68 |
-
conn = get_db_connection()
|
| 69 |
-
cursor = conn.cursor()
|
| 70 |
-
try:
|
| 71 |
-
cursor.execute("SELECT * FROM items")
|
| 72 |
-
items = cursor.fetchall()
|
| 73 |
-
# Convert sqlite3.Row objects to dictionaries for JSON serialization
|
| 74 |
-
return {"items": [dict(item) for item in items]}
|
| 75 |
-
except Exception as e:
|
| 76 |
-
raise HTTPException(status_code=500, detail=f"Error reading items: {e}")
|
| 77 |
-
finally:
|
| 78 |
-
cursor.close()
|
| 79 |
-
conn.close()
|
| 80 |
-
|
| 81 |
-
@app.get("/items/{item_id}")
|
| 82 |
-
async def read_item(item_id: int):
|
| 83 |
-
conn = get_db_connection()
|
| 84 |
-
cursor = conn.cursor()
|
| 85 |
-
try:
|
| 86 |
-
cursor.execute("SELECT * FROM items WHERE id = ?", (item_id,))
|
| 87 |
-
item = cursor.fetchone()
|
| 88 |
-
if item is None:
|
| 89 |
-
raise HTTPException(status_code=404, detail="Item not found")
|
| 90 |
-
return dict(item)
|
| 91 |
-
except Exception as e:
|
| 92 |
-
raise HTTPException(status_code=500, detail=f"Error reading item: {e}")
|
| 93 |
-
finally:
|
| 94 |
-
cursor.close()
|
| 95 |
-
conn.close()
|
| 96 |
-
|
| 97 |
@app.put("/items/{item_id}")
|
| 98 |
-
async def update_item(item_id: int,
|
| 99 |
conn = get_db_connection()
|
| 100 |
cursor = conn.cursor()
|
| 101 |
try:
|
| 102 |
updates = []
|
| 103 |
params = []
|
| 104 |
-
|
|
|
|
| 105 |
updates.append("name = ?")
|
| 106 |
-
params.append(name)
|
| 107 |
-
if description is not None:
|
| 108 |
updates.append("description = ?")
|
| 109 |
-
params.append(description)
|
| 110 |
|
| 111 |
if not updates:
|
| 112 |
raise HTTPException(status_code=400, detail="No fields to update provided")
|
|
@@ -129,19 +67,4 @@ async def update_item(item_id: int, name: str = None, description: str = None):
|
|
| 129 |
cursor.close()
|
| 130 |
conn.close()
|
| 131 |
|
| 132 |
-
|
| 133 |
-
async def delete_item(item_id: int):
|
| 134 |
-
conn = get_db_connection()
|
| 135 |
-
cursor = conn.cursor()
|
| 136 |
-
try:
|
| 137 |
-
cursor.execute("DELETE FROM items WHERE id = ?", (item_id,))
|
| 138 |
-
conn.commit()
|
| 139 |
-
if cursor.rowcount == 0:
|
| 140 |
-
raise HTTPException(status_code=404, detail="Item not found")
|
| 141 |
-
return {"message": "Item deleted successfully"}
|
| 142 |
-
except Exception as e:
|
| 143 |
-
conn.rollback()
|
| 144 |
-
raise HTTPException(status_code=500, detail=f"Error deleting item: {e}")
|
| 145 |
-
finally:
|
| 146 |
-
cursor.close()
|
| 147 |
-
conn.close()
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
|
| 3 |
from fastapi import FastAPI, HTTPException
|
| 4 |
+
from pydantic import BaseModel # <--- Import BaseModel
|
| 5 |
import sqlite3
|
| 6 |
import os
|
| 7 |
|
| 8 |
+
# Define the Pydantic model for Item creation/update
|
| 9 |
+
class Item(BaseModel):
|
| 10 |
+
name: str
|
| 11 |
+
description: str | None = None # Use Union type hint for None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
app = FastAPI()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
# ... rest of your existing code ...
|
|
|
|
|
|
|
| 16 |
|
| 17 |
@app.post("/items/")
|
| 18 |
+
async def create_item(item: Item): # <--- Change parameter to 'item: Item'
|
| 19 |
conn = get_db_connection()
|
| 20 |
cursor = conn.cursor()
|
| 21 |
try:
|
| 22 |
query = "INSERT INTO items (name, description) VALUES (?, ?)"
|
| 23 |
+
cursor.execute(query, (item.name, item.description)) # Access attributes using item.name, item.description
|
| 24 |
conn.commit()
|
| 25 |
return {"message": "Item created successfully", "id": cursor.lastrowid}
|
| 26 |
except Exception as e:
|
|
|
|
| 30 |
cursor.close()
|
| 31 |
conn.close()
|
| 32 |
|
| 33 |
+
# ... Also update your @app.put("/items/{item_id}") endpoint similarly ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
@app.put("/items/{item_id}")
|
| 35 |
+
async def update_item(item_id: int, item: Item): # <--- Change parameter to 'item: Item'
|
| 36 |
conn = get_db_connection()
|
| 37 |
cursor = conn.cursor()
|
| 38 |
try:
|
| 39 |
updates = []
|
| 40 |
params = []
|
| 41 |
+
|
| 42 |
+
if item.name is not None: # Access using item.name
|
| 43 |
updates.append("name = ?")
|
| 44 |
+
params.append(item.name)
|
| 45 |
+
if item.description is not None: # Access using item.description
|
| 46 |
updates.append("description = ?")
|
| 47 |
+
params.append(item.description)
|
| 48 |
|
| 49 |
if not updates:
|
| 50 |
raise HTTPException(status_code=400, detail="No fields to update provided")
|
|
|
|
| 67 |
cursor.close()
|
| 68 |
conn.close()
|
| 69 |
|
| 70 |
+
# ... rest of your existing code ...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|