user.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. from fastapi import APIRouter, Depends, HTTPException
  2. from sqlalchemy.orm import Session
  3. from app.api.dependencies.db import get_db
  4. from app.crud.crud_item import create_user_item
  5. from app.crud.crud_user import get_user_by_email, create_user, get_users, get_user
  6. from app.schemas.item import Item, ItemCreate
  7. from app.schemas.user import User, UserCreate
  8. router = APIRouter()
  9. @router.post("/", response_model=User)
  10. def create_new_user(user: UserCreate, db: Session = Depends(get_db)):
  11. db_user = get_user_by_email(db, email=user.email)
  12. if db_user:
  13. raise HTTPException(status_code=400, detail="Email already registered")
  14. return create_user(db=db, user=user)
  15. @router.get("/", response_model=list[User])
  16. def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
  17. users = get_users(db, skip=skip, limit=limit)
  18. return users
  19. @router.get("/{user_id}", response_model=User)
  20. def read_user(user_id: int, db: Session = Depends(get_db)):
  21. db_user = get_user(db, user_id=user_id)
  22. if db_user is None:
  23. raise HTTPException(status_code=404, detail="User not found")
  24. return db_user
  25. @router.post("/{user_id}/item", response_model=Item)
  26. def create_item_for_user(user_id: int, item: ItemCreate, db: Session = Depends(get_db)):
  27. return create_user_item(db, item=item, user_id=user_id)