91 lines
2.7 KiB
Python
91 lines
2.7 KiB
Python
from typing import Dict, Any
|
|
from sqlalchemy.orm import Session
|
|
from models.contact import Contact
|
|
from schemas.contact import ContactCreate, ContactSchema
|
|
from fastapi import HTTPException, status
|
|
from pydantic import ValidationError
|
|
|
|
def validate_contact_data(contact_data: Dict[str, Any]) -> Dict[str, str]:
|
|
"""
|
|
Validates contact form submission data using Pydantic schema validation.
|
|
|
|
Args:
|
|
contact_data (Dict[str, Any]): The contact form data to validate.
|
|
|
|
Returns:
|
|
Dict[str, str]: Dictionary of validation errors, empty if valid.
|
|
"""
|
|
errors = {}
|
|
|
|
try:
|
|
ContactCreate(**contact_data)
|
|
except ValidationError as e:
|
|
for error in e.errors():
|
|
field = error["loc"][0]
|
|
message = error["msg"]
|
|
errors[field] = message
|
|
|
|
return errors
|
|
|
|
def create_contact(db: Session, contact_data: ContactCreate) -> Contact:
|
|
"""
|
|
Creates a new contact submission in the database.
|
|
|
|
Args:
|
|
db (Session): The database session.
|
|
contact_data (ContactCreate): The validated contact form data.
|
|
|
|
Returns:
|
|
Contact: The newly created contact object.
|
|
|
|
Raises:
|
|
HTTPException: If there are validation errors with specific field details.
|
|
"""
|
|
try:
|
|
validated_data = contact_data.dict()
|
|
db_contact = Contact(**validated_data)
|
|
db.add(db_contact)
|
|
db.commit()
|
|
db.refresh(db_contact)
|
|
return db_contact
|
|
except ValidationError as e:
|
|
errors = {error["loc"][0]: error["msg"] for error in e.errors()}
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=errors
|
|
)
|
|
|
|
def format_contact_response(contact: Contact) -> ContactSchema:
|
|
"""
|
|
Formats a contact database object into the response schema.
|
|
|
|
Args:
|
|
contact (Contact): The contact database object.
|
|
|
|
Returns:
|
|
ContactSchema: The formatted contact response.
|
|
"""
|
|
return ContactSchema.from_orm(contact)
|
|
|
|
def sanitize_contact_input(contact_data: Dict[str, Any]) -> Dict[str, Any]:
|
|
"""
|
|
Sanitizes contact form input data using Pydantic schema validation.
|
|
|
|
Args:
|
|
contact_data (Dict[str, Any]): Raw contact form data.
|
|
|
|
Returns:
|
|
Dict[str, Any]: Sanitized contact form data.
|
|
|
|
Raises:
|
|
HTTPException: If required fields are missing or invalid with specific field details.
|
|
"""
|
|
try:
|
|
validated_data = ContactCreate(**contact_data)
|
|
return validated_data.dict()
|
|
except ValidationError as e:
|
|
errors = {error["loc"][0]: error["msg"] for error in e.errors()}
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=errors
|
|
) |