webapp-586ofu/helpers/contact_helpers.py

48 lines
1.2 KiB
Python

from sqlalchemy.orm import Session
from pydantic import ValidationError
from models.contact import Contact
from schemas.contact import ContactCreate
import re
def create_contact(db: Session, contact_data: ContactCreate) -> Contact:
"""
Creates a new contact in the database.
Args:
db (Session): The database session.
contact_data (ContactCreate): The data for the contact to create.
Returns:
Contact: The newly created contact object.
"""
db_contact = Contact(**contact_data.dict())
db.add(db_contact)
db.commit()
db.refresh(db_contact)
return db_contact
def validate_contact_data(contact_data: ContactCreate) -> bool:
"""
Validates the contact data.
Args:
contact_data (ContactCreate): The contact data to validate.
Returns:
bool: True if the data is valid, False otherwise.
"""
try:
contact_data.name
contact_data.email
contact_data.message
except ValidationError:
return False
if not contact_data.name or not contact_data.message:
return False
email_regex = r'^[\w\.-]+@[\w\.-]+\.\w+$'
if not re.match(email_regex, contact_data.email):
return False
return True