-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathapp.py
80 lines (58 loc) · 1.75 KB
/
app.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
from typing import Optional
from fastapi import FastAPI
from models import User, db
from pydantic import BaseModel
from fastapi_sqlalchemy import DBSessionMiddleware
app = FastAPI()
# Add SQLAlchemy session middleware to manage database sessions
app.add_middleware(DBSessionMiddleware, db=db)
# Endpoint to retrieve all users
@app.get("/users")
def get_users():
"""
Retrieve a list of all users.
Returns:
List[User]: A list of User objects.
"""
return User.query.all()
# Pydantic model for creating new users
class UserCreate(BaseModel):
name: str
email: str
# Endpoint to add a new user
@app.post("/add_user")
def add_user(user_data: UserCreate):
"""
Add a new user to the database.
Args:
user_data (UserCreate): User data including name and email.
Returns:
dict: A message indicating the success of the operation.
"""
user = User(**user_data.model_dump())
print(user)
user.save()
return {"message": "User created successfully"}
# Pydantic model for updating user information
class UserUpdate(UserCreate):
id: int
name: Optional[str]
email: Optional[str]
# Endpoint to update user information
@app.post("/update_user")
def update_user(user_data: UserUpdate):
"""
Update user information in the database.
Args:
user_data (UserUpdate): User data including ID, name, and email for updating.
Returns:
dict: A message indicating the success of the operation.
"""
user = User.query.filter_by(id=user_data.id).first()
print(user)
user.update(**user_data.model_dump())
user.save()
return {"message": "User updated successfully"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)