Skip to content

Commit

Permalink
added dto validation
Browse files Browse the repository at this point in the history
  • Loading branch information
mostafa6765 committed Dec 1, 2024
1 parent f1da544 commit c2c635a
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 27 deletions.
5 changes: 4 additions & 1 deletion fastapi_project/api/v1/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
7 changes: 4 additions & 3 deletions fastapi_project/services/user_service.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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")
Expand All @@ -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')
Expand Down
31 changes: 10 additions & 21 deletions fastapi_project/utils/base.py
Original file line number Diff line number Diff line change
@@ -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 = {}
Expand All @@ -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):
Expand Down Expand Up @@ -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__ = []
}
8 changes: 6 additions & 2 deletions fastapi_project/utils/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand All @@ -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']

0 comments on commit c2c635a

Please sign in to comment.