feat: Generated endpoint endpoints/email.post.py via AI for Contact_form and updated requirements.txt
This commit is contained in:
parent
1d69aeff0b
commit
8b577c443b
@ -0,0 +1,32 @@
|
||||
"""Initial creation of contact_forms table
|
||||
Revision ID: 9d6e4b3a5c2f
|
||||
Revises: 0001
|
||||
Create Date: 2023-08-03 10:24:35.123456
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '9d6e4b3a5c2f'
|
||||
down_revision = '0001'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table(
|
||||
'contact_forms',
|
||||
sa.Column('id', sa.String(36), primary_key=True),
|
||||
sa.Column('name', sa.String(), nullable=False),
|
||||
sa.Column('email', sa.String(), nullable=False),
|
||||
sa.Column('message', sa.Text(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), server_default=sa.func.now()),
|
||||
sa.Column('updated_at', sa.DateTime(), server_default=sa.func.now())
|
||||
)
|
||||
op.create_index(op.f('ix_contact_forms_email'), 'contact_forms', ['email'], unique=False)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index(op.f('ix_contact_forms_email'), table_name='contact_forms')
|
||||
op.drop_table('contact_forms')
|
@ -0,0 +1,20 @@
|
||||
from fastapi import APIRouter, Depends, status
|
||||
from sqlalchemy.orm import Session
|
||||
from core.database import get_db
|
||||
from schemas.contact_form import ContactFormCreate, ContactFormSchema
|
||||
from helpers.contact_form_helpers import handle_contact_form_submission
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/email", status_code=status.HTTP_201_CREATED, response_model=ContactFormSchema)
|
||||
async def submit_contact_form(
|
||||
form_data: ContactFormCreate,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Handle contact form submission with validation.
|
||||
|
||||
All fields (name, email, message) are required.
|
||||
Email must be in valid format.
|
||||
"""
|
||||
return handle_contact_form_submission(db=db, form_data=form_data)
|
137
helpers/contact_form_helpers.py
Normal file
137
helpers/contact_form_helpers.py
Normal file
@ -0,0 +1,137 @@
|
||||
from typing import Dict, Optional, Union, Any
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from email_validator import validate_email, EmailNotValidError
|
||||
from models.contact_form import ContactForm
|
||||
from schemas.contact_form import ContactFormCreate, ContactFormSchema
|
||||
|
||||
def validate_contact_form_data(
|
||||
form_data: Dict[str, Any]
|
||||
) -> Dict[str, Optional[str]]:
|
||||
"""
|
||||
Validates contact form data fields: name, email, and message.
|
||||
|
||||
Args:
|
||||
form_data (Dict[str, Any]): The contact form data to validate
|
||||
|
||||
Returns:
|
||||
Dict[str, Optional[str]]: Dictionary with field names as keys and error messages as values.
|
||||
If a field is valid, its error message will be None.
|
||||
"""
|
||||
errors = {
|
||||
"name": None,
|
||||
"email": None,
|
||||
"message": None
|
||||
}
|
||||
|
||||
# Validate name
|
||||
if "name" not in form_data or not form_data["name"]:
|
||||
errors["name"] = "Name is required"
|
||||
|
||||
# Validate email
|
||||
if "email" not in form_data or not form_data["email"]:
|
||||
errors["email"] = "Email is required"
|
||||
else:
|
||||
try:
|
||||
# Use email_validator to validate email format
|
||||
validate_email(form_data["email"])
|
||||
except EmailNotValidError:
|
||||
errors["email"] = "Invalid email format"
|
||||
|
||||
# Validate message
|
||||
if "message" not in form_data or not form_data["message"]:
|
||||
errors["message"] = "Message is required"
|
||||
|
||||
return errors
|
||||
|
||||
def validate_and_create_contact_form(
|
||||
db: Session,
|
||||
form_data: ContactFormCreate
|
||||
) -> Union[ContactForm, Dict[str, Optional[str]]]:
|
||||
"""
|
||||
Validates contact form data and creates a new contact form entry if valid.
|
||||
|
||||
Args:
|
||||
db (Session): The database session
|
||||
form_data (ContactFormCreate): The contact form data to validate and create
|
||||
|
||||
Returns:
|
||||
Union[ContactForm, Dict[str, Optional[str]]]:
|
||||
- ContactForm object if validation passes
|
||||
- Dictionary of validation errors if validation fails
|
||||
"""
|
||||
# Convert Pydantic model to dict for validation
|
||||
data_dict = form_data.dict()
|
||||
|
||||
# Validate the form data
|
||||
validation_errors = validate_contact_form_data(data_dict)
|
||||
|
||||
# Check if there are any validation errors
|
||||
if any(error is not None for error in validation_errors.values()):
|
||||
return validation_errors
|
||||
|
||||
# Create new contact form entry
|
||||
db_contact_form = ContactForm(**data_dict)
|
||||
db.add(db_contact_form)
|
||||
db.commit()
|
||||
db.refresh(db_contact_form)
|
||||
|
||||
return db_contact_form
|
||||
|
||||
def create_contact_form_entry(
|
||||
db: Session,
|
||||
form_data: ContactFormCreate
|
||||
) -> ContactForm:
|
||||
"""
|
||||
Creates a new contact form entry in the database.
|
||||
|
||||
Args:
|
||||
db (Session): The database session
|
||||
form_data (ContactFormCreate): The validated contact form data
|
||||
|
||||
Returns:
|
||||
ContactForm: The newly created contact form object
|
||||
"""
|
||||
db_contact_form = ContactForm(**form_data.dict())
|
||||
db.add(db_contact_form)
|
||||
db.commit()
|
||||
db.refresh(db_contact_form)
|
||||
return db_contact_form
|
||||
|
||||
def handle_contact_form_submission(
|
||||
db: Session,
|
||||
form_data: ContactFormCreate
|
||||
) -> ContactFormSchema:
|
||||
"""
|
||||
Process a contact form submission with validation.
|
||||
|
||||
Args:
|
||||
db (Session): The database session
|
||||
form_data (ContactFormCreate): The contact form data to process
|
||||
|
||||
Returns:
|
||||
ContactFormSchema: The created contact form entry
|
||||
|
||||
Raises:
|
||||
HTTPException: If validation fails with specific error messages
|
||||
"""
|
||||
# Validate the form data
|
||||
validation_errors = validate_contact_form_data(form_data.dict())
|
||||
|
||||
# Build error message if validation fails
|
||||
error_messages = []
|
||||
for field, error in validation_errors.items():
|
||||
if error:
|
||||
error_messages.append(f"{field}: {error}")
|
||||
|
||||
if error_messages:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail={"errors": error_messages}
|
||||
)
|
||||
|
||||
# Create the contact form entry
|
||||
contact_form = create_contact_form_entry(db, form_data)
|
||||
|
||||
# Return the created contact form
|
||||
return ContactFormSchema.from_orm(contact_form)
|
20
models/contact_form.py
Normal file
20
models/contact_form.py
Normal file
@ -0,0 +1,20 @@
|
||||
from sqlalchemy import Column, String, Text, DateTime
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.sql import func
|
||||
from core.database import Base
|
||||
import uuid
|
||||
|
||||
class ContactForm(Base):
|
||||
__tablename__ = "contact_forms"
|
||||
|
||||
# Primary key using UUID
|
||||
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
|
||||
# Contact form fields
|
||||
name = Column(String, nullable=False)
|
||||
email = Column(String, nullable=False, index=True)
|
||||
message = Column(Text, nullable=False)
|
||||
|
||||
# Timestamps
|
||||
created_at = Column(DateTime, default=func.now())
|
||||
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
|
@ -7,3 +7,7 @@ sqlalchemy>=1.4.0
|
||||
python-dotenv>=0.19.0
|
||||
bcrypt>=3.2.0
|
||||
alembic>=1.13.1
|
||||
email_validator
|
||||
jose
|
||||
passlib
|
||||
pydantic
|
||||
|
39
schemas/contact_form.py
Normal file
39
schemas/contact_form.py
Normal file
@ -0,0 +1,39 @@
|
||||
from pydantic import BaseModel, Field, EmailStr
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
# Base schema for ContactForm
|
||||
class ContactFormBase(BaseModel):
|
||||
name: str = Field(..., description="Name of the person submitting the form")
|
||||
email: EmailStr = Field(..., description="Email address of the person submitting the form")
|
||||
message: str = Field(..., description="Message content from the contact form")
|
||||
|
||||
# Schema for creating a new ContactForm
|
||||
class ContactFormCreate(ContactFormBase):
|
||||
pass
|
||||
|
||||
# Schema for updating an existing ContactForm
|
||||
class ContactFormUpdate(BaseModel):
|
||||
name: Optional[str] = Field(None, description="Name of the person submitting the form")
|
||||
email: Optional[EmailStr] = Field(None, description="Email address of the person submitting the form")
|
||||
message: Optional[str] = Field(None, description="Message content from the contact form")
|
||||
|
||||
# Schema for representing a ContactForm in responses
|
||||
class ContactFormSchema(ContactFormBase):
|
||||
id: UUID
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
orm_mode = True
|
||||
schema_extra = {
|
||||
"example": {
|
||||
"id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
|
||||
"name": "John Doe",
|
||||
"email": "john.doe@example.com",
|
||||
"message": "I would like more information about your services.",
|
||||
"created_at": "2023-01-01T12:00:00",
|
||||
"updated_at": "2023-01-01T12:00:00"
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user