Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
83 lines (61 loc) · 1.89 KB
/
Copy pathapp.py
File metadata and controls
83 lines (61 loc) · 1.89 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
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 DB session middleware with db_url specified
app.add_middleware(DBSessionMiddleware, db_url="sqlite:///example.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 db.session.query(User).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.dict())
db.session.add(user)
db.session.commit()
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 = db.session.query(User).filter_by(id=user_data.id).first()
if user_data.name:
user.name = user_data.name
if user_data.email:
user.email = user_data.email
db.session.add(user)
db.session.commit()
return {"message": "User updated successfully"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)