43 lines
1.5 KiB
Python
43 lines
1.5 KiB
Python
from sqlalchemy.orm import Session
|
|
from models.contact_form import ContactForm
|
|
from schemas.contact_form import ContactFormCreate
|
|
from fastapi import HTTPException
|
|
|
|
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.
|
|
"""
|
|
return ContactForm.validate_email(email)
|
|
|
|
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.message:
|
|
raise HTTPException(status_code=400, detail="Message is required")
|
|
if not contact_form_data.email or not ContactForm.validate_email(contact_form_data.email):
|
|
raise HTTPException(status_code=400, detail="Invalid email format")
|
|
|
|
db_contact_form = ContactForm(**contact_form_data.dict())
|
|
db.add(db_contact_form)
|
|
db.commit()
|
|
db.refresh(db_contact_form)
|
|
return db_contact_form |