diff --git a/fastapi_project/api/v1/user.py b/fastapi_project/api/v1/user.py index ce26a6d..55cecb9 100755 --- a/fastapi_project/api/v1/user.py +++ b/fastapi_project/api/v1/user.py @@ -16,7 +16,10 @@ async def create_order(request: Request): request_data = await the_query(request) data = UserCreateSchema(**request_data) - output = user_service.s_create_user(data) + # validated_data = request.state.validated_data + # output = user_service.s_create_user(request, validated_data) + + output = user_service.s_create_user(request, data) return JSONResponse(content=output, status_code=status.HTTP_200_OK) @router.get("/users") diff --git a/fastapi_project/services/user_service.py b/fastapi_project/services/user_service.py index 66ee1d0..651faf8 100755 --- a/fastapi_project/services/user_service.py +++ b/fastapi_project/services/user_service.py @@ -1,4 +1,4 @@ -from fastapi import HTTPException +from fastapi import HTTPException, Request from fastapi_project.database.database import SessionLocal from fastapi_project.utils.base import the_sorting, paginate from fastapi_project.models.users import User @@ -9,7 +9,8 @@ class UserService: def __init__(self): self.db = SessionLocal() - def s_create_user(self, user: UserCreateSchema): + def s_create_user(self, request: Request, user: UserCreateSchema): + db_user = self.db.query(User).filter(User.email == user.email).first() if db_user: raise HTTPException(status_code=400, detail="Email already registered") @@ -19,7 +20,7 @@ def s_create_user(self, user: UserCreateSchema): self.db.refresh(new_user) return new_user - def s_get_users(self, request): + def s_get_users(self, request: Request): users = self.db.query(User) users = the_sorting(request, users) return paginate(request, users, serilizer=UserSerializer, wrap='users') diff --git a/fastapi_project/utils/base.py b/fastapi_project/utils/base.py index 22b58e7..5c042ea 100755 --- a/fastapi_project/utils/base.py +++ b/fastapi_project/utils/base.py @@ -1,10 +1,8 @@ -from fastapi import Request, HTTPException +from fastapi import Request from typing import Any, Dict, Optional, Union from pydantic import BaseModel, ValidationError from sqlalchemy import desc from urllib.parse import urlparse -from fastapi.responses import JSONResponse -from fastapi import FastAPI async def the_query(request: Request, name = None) -> Dict[str, str]: data = {} @@ -23,22 +21,17 @@ async def the_query(request: Request, name = None) -> Dict[str, str]: async def validate_data(data: Dict[str, Any], model: BaseModel) -> Dict[str, Union[str, Dict[str, Any]]]: + output = {'status': 'valid'} + try: instance = model(**data) - return {'success': True, 'data': instance.dict()} + output['data'] = instance.dict() except ValidationError as e: - errors = {} - for error in e.errors(): - field = error['loc'][0] - message = field + " " + error['msg'] - if field not in errors: - errors[field] = [] - errors[field].append(message) - - return { - 'success': False, - 'errors': errors["details"] - } + # If validation fails, return status as invalid and the validation errors + output['status'] = 'invalid' + output['errors'] = e.errors() + + return output def the_sorting(request, query): @@ -103,8 +96,4 @@ def paginate(request: Request, query, serilizer, the_page: int = 1, the_per_page 'from': offset + 1 if data else None, 'to': offset + len(data) if data else None, wrap: data - } - - -# Update the __all__ list -__all__ = [] \ No newline at end of file + } \ No newline at end of file diff --git a/fastapi_project/utils/validation.py b/fastapi_project/utils/validation.py index 7a9d58d..2237820 100644 --- a/fastapi_project/utils/validation.py +++ b/fastapi_project/utils/validation.py @@ -27,7 +27,11 @@ async def wrapper(request: Request, *args, **kwargs): try: request_data = await the_query(request) validated_data = schema(**request_data) - return await func(validated_data, *args, **kwargs) + + # Attach validated data to request object + request.state.validated_data = validated_data + + return await func(request, *args, **kwargs) except ValidationError as e: errors = {} for error in e.errors(): @@ -48,4 +52,4 @@ async def wrapper(request: Request, *args, **kwargs): return decorator # Update the __all__ list -__all__ = ['dto', 'ValidationException', 'setup_validation_exception_handler'] +__all__ = ['dto', 'ValidationException', 'setup_validation_exception_handler'] \ No newline at end of file