forked from microsoft/github-copilot-vibe-coding-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
454 lines (371 loc) · 14.9 KB
/
Copy pathmain.py
File metadata and controls
454 lines (371 loc) · 14.9 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
"""
FastAPI Social Media API
A simple social networking service API for posts, comments, and likes.
"""
import yaml
from typing import List
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from models import (
Post, Comment, Like, Error,
CreatePostRequest, UpdatePostRequest,
CreateCommentRequest, UpdateCommentRequest,
LikeRequest, UnlikeRequest
)
from database import (
init_database, get_db_connection, update_post_counts,
get_all_posts, get_post_by_id, create_post, update_post, delete_post, post_exists,
get_comments_by_post_id, get_comment_by_id, create_comment, update_comment, delete_comment, comment_exists,
get_like, create_like, delete_like, like_exists
)
# Load the OpenAPI specification
def load_openapi_spec():
"""Load the OpenAPI specification from the yaml file"""
with open("/workspaces/github-copilot-vibe-coding-workshop/openapi.yaml", "r") as file:
return yaml.safe_load(file)
# Lifespan event for database initialization
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
init_database()
yield
# Shutdown - nothing to clean up
# FastAPI app with custom OpenAPI configuration
app = FastAPI(
lifespan=lifespan,
title="Simple Social Media API",
description="A basic Social Networking Service API that allows users to create, retrieve, update, and delete posts; add comments; and like/unlike posts.",
version="1.0.0",
contact={
"name": "Contoso Team",
"email": "team@contoso.com"
},
servers=[{"url": "http://localhost:8000/api", "description": "Local development server"}],
docs_url="/docs",
redoc_url="/redoc"
)
# Override the default OpenAPI schema with our custom one
def custom_openapi():
"""Override FastAPI's default OpenAPI generation"""
if app.openapi_schema:
return app.openapi_schema
# Load and return the exact OpenAPI specification from the YAML file
openapi_schema = load_openapi_spec()
app.openapi_schema = openapi_schema
return app.openapi_schema
app.openapi = custom_openapi
# Add CORS middleware to allow all origins
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allow all origins
allow_credentials=True,
allow_methods=["*"], # Allow all methods
allow_headers=["*"], # Allow all headers
)
# API Endpoints
@app.get("/api/posts", response_model=List[Post])
async def list_posts():
"""List all posts"""
try:
conn = get_db_connection()
posts = get_all_posts(conn)
conn.close()
return [
Post(
id=post["id"],
username=post["username"],
content=post["content"],
created_at=post["created_at"],
updated_at=post["updated_at"],
like_count=post["like_count"],
comment_count=post["comment_count"]
)
for post in posts
]
except Exception as e:
raise HTTPException(status_code=500, detail={"error": "InternalServerError", "message": str(e)})
@app.post("/api/posts", response_model=Post, status_code=201)
async def create_post_endpoint(request: CreatePostRequest):
"""Create a new post"""
try:
conn = get_db_connection()
post_id = create_post(request.username, request.content, conn)
conn.commit()
# Fetch the created post
post = get_post_by_id(post_id, conn)
conn.close()
return Post(
id=post["id"],
username=post["username"],
content=post["content"],
created_at=post["created_at"],
updated_at=post["updated_at"],
like_count=post["like_count"],
comment_count=post["comment_count"]
)
except Exception as e:
raise HTTPException(status_code=500, detail={"error": "InternalServerError", "message": str(e)})
@app.get("/api/posts/{post_id}", response_model=Post)
async def get_post(post_id: int):
"""Get a specific post"""
try:
conn = get_db_connection()
post = get_post_by_id(post_id, conn)
conn.close()
if not post:
raise HTTPException(status_code=404, detail={"error": "NotFound", "message": "Post not found"})
return Post(
id=post["id"],
username=post["username"],
content=post["content"],
created_at=post["created_at"],
updated_at=post["updated_at"],
like_count=post["like_count"],
comment_count=post["comment_count"]
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail={"error": "InternalServerError", "message": str(e)})
@app.patch("/api/posts/{post_id}", response_model=Post)
async def update_post_endpoint(post_id: int, request: UpdatePostRequest):
"""Update a post"""
try:
conn = get_db_connection()
# Check if post exists
if not post_exists(post_id, conn):
conn.close()
raise HTTPException(status_code=404, detail={"error": "NotFound", "message": "Post not found"})
# Update the post
update_post(post_id, request.username, request.content, conn)
conn.commit()
# Fetch the updated post
post = get_post_by_id(post_id, conn)
conn.close()
return Post(
id=post["id"],
username=post["username"],
content=post["content"],
created_at=post["created_at"],
updated_at=post["updated_at"],
like_count=post["like_count"],
comment_count=post["comment_count"]
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail={"error": "InternalServerError", "message": str(e)})
@app.delete("/api/posts/{post_id}", status_code=204)
async def delete_post_endpoint(post_id: int):
"""Delete a post"""
try:
conn = get_db_connection()
# Check if post exists
if not post_exists(post_id, conn):
conn.close()
raise HTTPException(status_code=404, detail={"error": "NotFound", "message": "Post not found"})
# Delete the post and related data
delete_post(post_id, conn)
conn.commit()
conn.close()
return None
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail={"error": "InternalServerError", "message": str(e)})
@app.get("/api/posts/{post_id}/comments", response_model=List[Comment])
async def list_comments(post_id: int):
"""List comments for a post"""
try:
conn = get_db_connection()
# Check if post exists
if not post_exists(post_id, conn):
conn.close()
raise HTTPException(status_code=404, detail={"error": "NotFound", "message": "Post not found"})
# Get comments
comments = get_comments_by_post_id(post_id, conn)
conn.close()
return [
Comment(
id=comment["id"],
post_id=comment["post_id"],
username=comment["username"],
content=comment["content"],
created_at=comment["created_at"],
updated_at=comment["updated_at"]
)
for comment in comments
]
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail={"error": "InternalServerError", "message": str(e)})
@app.post("/api/posts/{post_id}/comments", response_model=Comment, status_code=201)
async def create_comment_endpoint(post_id: int, request: CreateCommentRequest):
"""Create a comment"""
try:
conn = get_db_connection()
# Check if post exists
if not post_exists(post_id, conn):
conn.close()
raise HTTPException(status_code=404, detail={"error": "NotFound", "message": "Post not found"})
# Create comment
comment_id = create_comment(post_id, request.username, request.content, conn)
# Update post comment count
update_post_counts(post_id, conn)
conn.commit()
# Fetch the created comment
comment = get_comment_by_id(comment_id, post_id, conn)
conn.close()
return Comment(
id=comment["id"],
post_id=comment["post_id"],
username=comment["username"],
content=comment["content"],
created_at=comment["created_at"],
updated_at=comment["updated_at"]
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail={"error": "InternalServerError", "message": str(e)})
@app.get("/api/posts/{post_id}/comments/{comment_id}", response_model=Comment)
async def get_comment(post_id: int, comment_id: int):
"""Get a specific comment"""
try:
conn = get_db_connection()
# Check if post exists
if not post_exists(post_id, conn):
conn.close()
raise HTTPException(status_code=404, detail={"error": "NotFound", "message": "Post not found"})
# Get comment
comment = get_comment_by_id(comment_id, post_id, conn)
conn.close()
if not comment:
raise HTTPException(status_code=404, detail={"error": "NotFound", "message": "Comment not found"})
return Comment(
id=comment["id"],
post_id=comment["post_id"],
username=comment["username"],
content=comment["content"],
created_at=comment["created_at"],
updated_at=comment["updated_at"]
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail={"error": "InternalServerError", "message": str(e)})
@app.patch("/api/posts/{post_id}/comments/{comment_id}", response_model=Comment)
async def update_comment_endpoint(post_id: int, comment_id: int, request: UpdateCommentRequest):
"""Update a comment"""
try:
conn = get_db_connection()
# Check if post exists
if not post_exists(post_id, conn):
conn.close()
raise HTTPException(status_code=404, detail={"error": "NotFound", "message": "Post not found"})
# Check if comment exists
if not comment_exists(comment_id, post_id, conn):
conn.close()
raise HTTPException(status_code=404, detail={"error": "NotFound", "message": "Comment not found"})
# Update the comment
update_comment(comment_id, post_id, request.username, request.content, conn)
conn.commit()
# Fetch the updated comment
comment = get_comment_by_id(comment_id, post_id, conn)
conn.close()
return Comment(
id=comment["id"],
post_id=comment["post_id"],
username=comment["username"],
content=comment["content"],
created_at=comment["created_at"],
updated_at=comment["updated_at"]
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail={"error": "InternalServerError", "message": str(e)})
@app.delete("/api/posts/{post_id}/comments/{comment_id}", status_code=204)
async def delete_comment_endpoint(post_id: int, comment_id: int):
"""Delete a comment"""
try:
conn = get_db_connection()
# Check if post exists
if not post_exists(post_id, conn):
conn.close()
raise HTTPException(status_code=404, detail={"error": "NotFound", "message": "Post not found"})
# Check if comment exists
if not comment_exists(comment_id, post_id, conn):
conn.close()
raise HTTPException(status_code=404, detail={"error": "NotFound", "message": "Comment not found"})
# Delete the comment
delete_comment(comment_id, post_id, conn)
# Update post comment count
update_post_counts(post_id, conn)
conn.commit()
conn.close()
return None
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail={"error": "InternalServerError", "message": str(e)})
@app.post("/api/posts/{post_id}/likes", response_model=Like, status_code=201)
async def like_post(post_id: int, request: LikeRequest):
"""Like a post"""
try:
conn = get_db_connection()
# Check if post exists
if not post_exists(post_id, conn):
conn.close()
raise HTTPException(status_code=404, detail={"error": "NotFound", "message": "Post not found"})
# Check if user already liked this post
if like_exists(post_id, request.username, conn):
conn.close()
raise HTTPException(status_code=400, detail={"error": "ValidationError", "message": "Post already liked by user"})
# Create like
like_id = create_like(post_id, request.username, conn)
# Update post like count
update_post_counts(post_id, conn)
conn.commit()
# Fetch the created like
like = get_like(post_id, request.username, conn)
conn.close()
return Like(
id=like["id"],
post_id=like["post_id"],
username=like["username"],
created_at=like["created_at"]
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail={"error": "InternalServerError", "message": str(e)})
@app.delete("/api/posts/{post_id}/likes", status_code=204)
async def unlike_post(post_id: int, request: UnlikeRequest):
"""Unlike a post"""
try:
conn = get_db_connection()
# Check if post exists
if not post_exists(post_id, conn):
conn.close()
raise HTTPException(status_code=404, detail={"error": "NotFound", "message": "Post not found"})
# Check if user has liked this post
if not like_exists(post_id, request.username, conn):
conn.close()
raise HTTPException(status_code=400, detail={"error": "ValidationError", "message": "Post not currently liked by user"})
# Delete the like
delete_like(post_id, request.username, conn)
# Update post like count
update_post_counts(post_id, conn)
conn.commit()
conn.close()
return None
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail={"error": "InternalServerError", "message": str(e)})
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)