44 lines
2.2 KiB
Python
44 lines
2.2 KiB
Python
Here's the `user.py` file for the specified routes:
|
|
|
|
```python
|
|
from typing import List
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.api.v1.models.user import User
|
|
from app.api.v1.schemas.user import UserCreate, UserResponse
|
|
from app.api.core.dependencies.dependencies import get_db
|
|
|
|
router = APIRouter()
|
|
|
|
@router.get("/users", response_model=List[UserResponse])
|
|
def read_users(db: Session = Depends(get_db)):
|
|
users = db.query(User).all()
|
|
return users
|
|
|
|
@router.post("/users", response_model=UserResponse)
|
|
def create_user(user: UserCreate, db: Session = Depends(get_db)):
|
|
db_user = User(**user.dict())
|
|
db.add(db_user)
|
|
db.commit()
|
|
db.refresh(db_user)
|
|
return db_user
|
|
|
|
@router.get("/users/{user_id}", response_model=UserResponse)
|
|
def read_user(user_id: int, db: Session = Depends(get_db)):
|
|
db_user = db.query(User).filter(User.id == user_id).first()
|
|
if not db_user:
|
|
raise HTTPException(status_code=404, detail="User not found")
|
|
return db_user
|
|
```
|
|
|
|
Explanation:
|
|
|
|
1. We import the necessary modules and dependencies.
|
|
2. We create an instance of `APIRouter` to define the routes.
|
|
3. The `read_users` function handles the `GET /users` route. It fetches all users from the database using `db.query(User).all()` and returns them as a list of `UserResponse` models.
|
|
4. The `create_user` function handles the `POST /users` route. It takes a `UserCreate` model as input, creates a new `User` instance from the input data, adds it to the database session, commits the changes, and returns the newly created user as a `UserResponse` model.
|
|
5. The `read_user` function handles the `GET /users/{user_id}` route. It fetches a user from the database based on the provided `user_id`. If the user is not found, it raises an `HTTPException` with a 404 status code. Otherwise, it returns the user as a `UserResponse` model.
|
|
6. All routes use the `get_db` dependency to obtain a database session.
|
|
|
|
Note: This code assumes that you have defined the `User` model in `app.api.v1.models.user` and the `UserCreate` and `UserResponse` schemas in `app.api.v1.schemas.user`. Additionally, the `get_db` dependency should be defined in `app.api.core.dependencies.dependencies`. |