project-three-6eu16p/helpers/contact_form_helpers.py

50 lines
1.6 KiB
Python

from sqlalchemy.orm import Session
from models.contact_form import ContactForm
from schemas.contact_form import ContactFormCreate
from fastapi import HTTPException
import email_validator
def validate_email(email: str) -> bool:
"""
Validates the provided email address using the email_validator package.
Args:
email (str): The email address to validate.
Returns:
bool: True if the email is valid, False otherwise.
"""
try:
email_validator.validate_email(email)
return True
except email_validator.EmailNotValidError:
return False
def create_contact_form(db: Session, contact_form_data: ContactFormCreate) -> ContactForm:
"""
Creates a new contact form in the database.
Args:
db (Session): The database session.
contact_form_data (ContactFormCreate): The data for the contact form to create.
Returns:
ContactForm: The newly created contact form object.
Raises:
HTTPException: If any required field is missing or the email is invalid.
"""
if not contact_form_data.name:
raise HTTPException(status_code=400, detail="Name is required")
if not contact_form_data.email:
raise HTTPException(status_code=400, detail="Email is required")
if not validate_email(contact_form_data.email):
raise HTTPException(status_code=400, detail="Invalid email format")
if not contact_form_data.message:
raise HTTPException(status_code=400, detail="Message is required")
db_contact_form = ContactForm(**contact_form_data.dict())
db.add(db_contact_form)
db.commit()
db.refresh(db_contact_form)
return db_contact_form