-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
76 lines (64 loc) · 2.42 KB
/
main.py
File metadata and controls
76 lines (64 loc) · 2.42 KB
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
71
72
73
74
75
76
from fastapi import FastAPI, HTTPException
from typing import List
import sqlite3
import database, models
app = FastAPI(title="ToDo Service")
database.init_db()
def get_db_connection():
conn = sqlite3.connect(database.DATABASE_PATH)
conn.row_factory = sqlite3.Row
return conn
@app.post("/items", response_model=models.Item, status_code=201)
def create_item(item: models.ItemCreate):
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute(
"INSERT INTO items (title, description, completed) VALUES (?, ?, ?)",
(item.title, item.description, item.completed)
)
item_id = cursor.lastrowid
conn.commit()
conn.close()
return {**item.dict(), "id": item_id}
@app.get("/items", response_model=List[models.Item])
def read_items():
conn = get_db_connection()
items = conn.execute("SELECT * FROM items").fetchall()
conn.close()
return [dict(item) for item in items]
@app.get("/items/{item_id}", response_model=models.Item)
def read_item(item_id: int):
conn = get_db_connection()
item = conn.execute("SELECT * FROM items WHERE id = ?", (item_id,)).fetchone()
conn.close()
if item is None:
raise HTTPException(status_code=404, detail="Item not found")
return dict(item)
@app.put("/items/{item_id}", response_model=models.Item)
def update_item(item_id: int, item_update: models.ItemUpdate):
conn = get_db_connection()
current = conn.execute("SELECT * FROM items WHERE id = ?", (item_id,)).fetchone()
if current is None:
conn.close()
raise HTTPException(status_code=404, detail="Item not found")
update_data = item_update.dict(exclude_unset=True)
if not update_data:
conn.close()
return dict(current)
set_clause = ", ".join([f"{k} = ?" for k in update_data.keys()])
values = list(update_data.values()) + [item_id]
conn.execute(f"UPDATE items SET {set_clause} WHERE id = ?", values)
conn.commit()
updated = conn.execute("SELECT * FROM items WHERE id = ?", (item_id,)).fetchone()
conn.close()
return dict(updated)
@app.delete("/items/{item_id}", status_code=204)
def delete_item(item_id: int):
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("DELETE FROM items WHERE id = ?", (item_id,))
if cursor.rowcount == 0:
conn.close()
raise HTTPException(status_code=404, detail="Item not found")
conn.commit()
conn.close()