-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwarmup.py
176 lines (155 loc) · 4.75 KB
/
warmup.py
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
from fastapi import FastAPI
from typing import List, Optional
from pydantic import BaseModel
from datetime import datetime
import sqlite3
from fastapi import HTTPException, Depends, status
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
# Models
class User(BaseModel):
id: Optional[int] = None
email: str
name: str
created_at: Optional[datetime] = None
class Trip(BaseModel):
id: Optional[int] = None
user_id: int
title: str
description: Optional[str] = None
start_date: datetime
end_date: datetime
class Photo(BaseModel):
id: Optional[int] = None
trip_id: int
filename: str
coordinates: Optional[tuple] = None
taken_at: Optional[datetime] = None
# Database connection
def get_db():
conn = sqlite3.connect('travel.db')
try:
conn.row_factory = sqlite3.Row
yield conn
finally:
conn.close()
# Authentication middleware (simplified)
async def get_current_user(db: sqlite3.Connection = Depends(get_db)):
# In real app, would verify JWT token
return {"id": 1, "email": "[email protected]"}
# CRUD Operations
@app.post("/users/", response_model=User, status_code=status.HTTP_201_CREATED)
async def create_user(user: User, db: sqlite3.Connection = Depends(get_db)):
cursor = db.cursor()
cursor.execute(
"INSERT INTO users (email, name) VALUES (?, ?) RETURNING *",
(user.email, user.name)
)
db.commit()
return dict(cursor.fetchone())
@app.get("/users/{user_id}", response_model=User)
async def get_user(user_id: int, db: sqlite3.Connection = Depends(get_db)):
cursor = db.cursor()
result = cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
user = result.fetchone()
if not user:
raise HTTPException(status_code=404, detail="User not found")
return dict(user)
# Trips endpoints
@app.post("/trips/", response_model=Trip)
async def create_trip(
trip: Trip,
current_user = Depends(get_current_user),
db: sqlite3.Connection = Depends(get_db)
):
cursor = db.cursor()
cursor.execute(
"""INSERT INTO trips (user_id, title, description, start_date, end_date)
VALUES (?, ?, ?, ?, ?) RETURNING *""",
(current_user["id"], trip.title, trip.description,
trip.start_date, trip.end_date)
)
db.commit()
return dict(cursor.fetchone())
@app.get("/trips/", response_model=List[Trip])
async def list_trips(
skip: int = 0,
limit: int = 10,
db: sqlite3.Connection = Depends(get_db)
):
cursor = db.cursor()
cursor.execute(
"SELECT * FROM trips LIMIT ? OFFSET ?",
(limit, skip)
)
return [dict(row) for row in cursor.fetchall()]
# Search endpoint with filtering
@app.get("/search/trips/")
async def search_trips(
start_date: Optional[datetime] = None,
end_date: Optional[datetime] = None,
title: Optional[str] = None,
db: sqlite3.Connection = Depends(get_db)
):
query = "SELECT * FROM trips WHERE 1=1"
params = []
if start_date:
query += " AND start_date >= ?"
params.append(start_date)
if end_date:
query += " AND end_date <= ?"
params.append(end_date)
if title:
query += " AND title LIKE ?"
params.append(f"%{title}%")
cursor = db.cursor()
cursor.execute(query, params)
return [dict(row) for row in cursor.fetchall()]
# File upload endpoint
@app.post("/trips/{trip_id}/photos/")
async def upload_photo(
trip_id: int,
photo: Photo,
current_user = Depends(get_current_user),
db: sqlite3.Connection = Depends(get_db)
):
# Verify trip belongs to user
cursor = db.cursor()
cursor.execute(
"SELECT * FROM trips WHERE id = ? AND user_id = ?",
(trip_id, current_user["id"])
)
if not cursor.fetchone():
raise HTTPException(
status_code=403,
detail="Not authorized to upload to this trip"
)
cursor.execute(
"""INSERT INTO photos (trip_id, filename, coordinates, taken_at)
VALUES (?, ?, ?, ?) RETURNING *""",
(trip_id, photo.filename, photo.coordinates, photo.taken_at)
)
db.commit()
return dict(cursor.fetchone())
# Aggregation endpoint
@app.get("/trips/stats/")
async def get_trip_stats(db: sqlite3.Connection = Depends(get_db)):
cursor = db.cursor()
cursor.execute("""
SELECT
COUNT(*) as total_trips,
AVG(JULIANDAY(end_date) - JULIANDAY(start_date)) as avg_duration,
COUNT(DISTINCT user_id) as unique_users
FROM trips
""")
return dict(cursor.fetchone())
# Health check endpoint
@app.get("/health")
async def health_check():
return {
"status": "healthy",
"timestamp": datetime.utcnow(),
"version": "1.0.0"
}