-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.py
More file actions
200 lines (159 loc) · 5.34 KB
/
main.py
File metadata and controls
200 lines (159 loc) · 5.34 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""
FastAPI Integration Example with sqlite-worker
This example demonstrates how to integrate sqlite-worker with FastAPI
for building a simple REST API with thread-safe database operations.
"""
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from sqlite_worker import SqliteWorker
from typing import List, Optional
import os
# Initialize FastAPI app
app = FastAPI(title="SQLite Worker FastAPI Demo")
# Initialize database worker
DB_PATH = os.path.join(os.path.dirname(__file__), "app.db")
worker = SqliteWorker(
DB_PATH,
execute_init=[
"PRAGMA journal_mode=WAL;",
"PRAGMA synchronous=NORMAL;",
"PRAGMA temp_store=MEMORY;"
],
max_count=50
)
# Initialize database schema
worker.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
age INTEGER
)
""")
# Pydantic models
class UserCreate(BaseModel):
name: str
email: str
age: Optional[int] = None
class User(BaseModel):
id: int
name: str
email: str
age: Optional[int] = None
class UserUpdate(BaseModel):
name: Optional[str] = None
email: Optional[str] = None
age: Optional[int] = None
# API Endpoints
@app.get("/")
def read_root():
"""Health check endpoint"""
return {"message": "SQLite Worker FastAPI Demo", "status": "running"}
@app.post("/users", response_model=User)
def create_user(user: UserCreate):
"""Create a new user"""
try:
data = {"name": user.name, "email": user.email}
if user.age is not None:
data["age"] = user.age
token = worker.insert("users", data)
result = worker.fetch_results(token)
# Get the created user
token = worker.select("users", conditions={"email": user.email})
users = worker.fetch_results(token)
if users:
return User(
id=users[0][0],
name=users[0][1],
email=users[0][2],
age=users[0][3]
)
raise HTTPException(status_code=500, detail="User created but not found")
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.get("/users", response_model=List[User])
def list_users(limit: int = 100):
"""List all users"""
try:
token = worker.select("users", limit=limit)
users = worker.fetch_results(token)
return [
User(id=u[0], name=u[1], email=u[2], age=u[3])
for u in users
]
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/users/{user_id}", response_model=User)
def get_user(user_id: int):
"""Get a specific user by ID"""
try:
token = worker.select("users", conditions={"id": user_id})
users = worker.fetch_results(token)
if not users:
raise HTTPException(status_code=404, detail="User not found")
return User(
id=users[0][0],
name=users[0][1],
email=users[0][2],
age=users[0][3]
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.put("/users/{user_id}", response_model=User)
def update_user(user_id: int, user_update: UserUpdate):
"""Update a user"""
try:
# Check if user exists
token = worker.select("users", conditions={"id": user_id})
users = worker.fetch_results(token)
if not users:
raise HTTPException(status_code=404, detail="User not found")
# Build update data
update_data = {}
if user_update.name is not None:
update_data["name"] = user_update.name
if user_update.email is not None:
update_data["email"] = user_update.email
if user_update.age is not None:
update_data["age"] = user_update.age
if update_data:
token = worker.update("users", update_data, {"id": user_id})
worker.fetch_results(token)
# Return updated user
token = worker.select("users", conditions={"id": user_id})
users = worker.fetch_results(token)
return User(
id=users[0][0],
name=users[0][1],
email=users[0][2],
age=users[0][3]
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
@app.delete("/users/{user_id}")
def delete_user(user_id: int):
"""Delete a user"""
try:
# Check if user exists
token = worker.select("users", conditions={"id": user_id})
users = worker.fetch_results(token)
if not users:
raise HTTPException(status_code=404, detail="User not found")
token = worker.delete("users", {"id": user_id})
worker.fetch_results(token)
return {"message": "User deleted successfully"}
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.on_event("shutdown")
def shutdown_event():
"""Cleanup on shutdown"""
worker.close()
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)