11import app .schemas as schemas , app .models as models
22from sqlalchemy .orm import Session
3+ from sqlalchemy .exc import IntegrityError
4+ from pydantic import ValidationError
35from fastapi import Depends , HTTPException , status , APIRouter
46from app .database import get_db
57
68router = APIRouter ()
79
810
11+ @router .post (
12+ "/" , status_code = status .HTTP_201_CREATED , response_model = schemas .CreateUserResponse
13+ )
14+ def create_user (payload : schemas .UserBaseSchema , db : Session = Depends (get_db )):
15+ try :
16+ # Create a new user instance from the payload
17+ new_user = models .User (** payload .dict ())
18+ db .add (new_user )
19+ db .commit ()
20+ db .refresh (new_user )
21+
22+ except IntegrityError as e :
23+ db .rollback ()
24+ # Log the error or handle it as needed
25+ raise HTTPException (
26+ status_code = status .HTTP_409_CONFLICT ,
27+ detail = "A user with the given details already exists." ,
28+ ) from e
29+ except Exception as e :
30+ db .rollback ()
31+ # Handle other types of database errors
32+ raise HTTPException (
33+ status_code = status .HTTP_500_INTERNAL_SERVER_ERROR ,
34+ detail = "An error occurred while creating the user." ,
35+ ) from e
36+
37+ # Convert the SQLAlchemy model instance to a Pydantic model
38+ user_schema = schemas .UserBaseSchema .from_orm (new_user )
39+ # Return the successful creation response
40+ return schemas .CreateUserResponse (Status = schemas .Status .Success , User = user_schema )
41+
42+
943@router .get ("/" , status_code = status .HTTP_200_OK )
1044def get_users (
1145 db : Session = Depends (get_db ), limit : int = 10 , page : int = 1 , search : str = ""
@@ -22,15 +56,6 @@ def get_users(
2256 return {"Status" : "Success" , "Results" : len (users ), "Users" : users }
2357
2458
25- @router .post ("/" , status_code = status .HTTP_201_CREATED )
26- def create_user (payload : schemas .UserBaseSchema , db : Session = Depends (get_db )):
27- new_user = models .User (** payload .dict ())
28- db .add (new_user )
29- db .commit ()
30- db .refresh (new_user )
31- return {"Status" : "Success" , "User" : new_user }
32-
33-
3459@router .patch ("/{userId}" , status_code = status .HTTP_202_ACCEPTED )
3560def update_user (
3661 userId : str , payload : schemas .UserBaseSchema , db : Session = Depends (get_db )
0 commit comments