63 lines
1.9 KiB
Python
63 lines
1.9 KiB
Python
import re
|
|
from sqlalchemy.orm import Session
|
|
from fastapi import HTTPException
|
|
from models.contact_form import ContactForm
|
|
from schemas.contact_form import ContactFormCreate
|
|
import email_validator
|
|
|
|
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.
|
|
"""
|
|
validate_contact_form_data(contact_form_data)
|
|
db_contact_form = ContactForm(**contact_form_data.dict())
|
|
db.add(db_contact_form)
|
|
db.commit()
|
|
db.refresh(db_contact_form)
|
|
return db_contact_form
|
|
|
|
def validate_contact_form_data(contact_form_data: ContactFormCreate):
|
|
"""
|
|
Validates the contact form data.
|
|
|
|
Args:
|
|
contact_form_data (ContactFormCreate): The contact form data to validate.
|
|
|
|
Raises:
|
|
HTTPException: If any validation fails.
|
|
"""
|
|
name = contact_form_data.name
|
|
email = contact_form_data.email
|
|
message = contact_form_data.message
|
|
|
|
if not name:
|
|
raise HTTPException(status_code=400, detail="Name is required")
|
|
if not email:
|
|
raise HTTPException(status_code=400, detail="Email is required")
|
|
if not message:
|
|
raise HTTPException(status_code=400, detail="Message is required")
|
|
|
|
try:
|
|
email_validator.validate_email(email)
|
|
except email_validator.EmailNotValidError as e:
|
|
raise HTTPException(status_code=400, detail=str(e))
|
|
|
|
def validate_email(email: str) -> bool:
|
|
"""
|
|
Validates an email address using a regular expression.
|
|
|
|
Args:
|
|
email (str): The email address to validate.
|
|
|
|
Returns:
|
|
bool: True if the email is valid, False otherwise.
|
|
"""
|
|
email_regex = r'^[\w\.-]+@[\w\.-]+\.\w+$'
|
|
return bool(re.match(email_regex, email)) |