feat: Generated endpoint endpoints/names.post.py via AI for Contact_form
This commit is contained in:
parent
6b0b5cc2ff
commit
52db66c5e5
@ -0,0 +1,32 @@
|
|||||||
|
"""Initial creation of contact_forms table
|
||||||
|
Revision ID: 9a2c5f7e1d3b
|
||||||
|
Revises: 0001
|
||||||
|
Create Date: 2023-11-08 10:25:00.000000
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '9a2c5f7e1d3b'
|
||||||
|
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,34 @@
|
|||||||
|
from fastapi import APIRouter, HTTPException, status, Depends
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from core.database import get_db
|
||||||
|
from schemas.contactform import ContactFormCreate, ContactFormSchema
|
||||||
|
from helpers.contactform_helpers import validate_contact_form_data, create_contact_form, format_validation_error_response, send_notification_email
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.post("/names", 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 submissions with validation for required fields and email format.
|
||||||
|
"""
|
||||||
|
# Validate the form data
|
||||||
|
validation_errors = validate_contact_form_data(form_data.dict())
|
||||||
|
|
||||||
|
# If there are validation errors, return a 400 response with details
|
||||||
|
if validation_errors:
|
||||||
|
error_response = format_validation_error_response(validation_errors)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail=error_response
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create the contact form entry in the database
|
||||||
|
contact_form = create_contact_form(db=db, form_data=form_data)
|
||||||
|
|
||||||
|
# Send notification email (in a real application, this might be done asynchronously)
|
||||||
|
send_notification_email(contact_form)
|
||||||
|
|
||||||
|
return contact_form
|
99
helpers/contact_form_helpers.py
Normal file
99
helpers/contact_form_helpers.py
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
from typing import Optional, Dict, Any
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from email_validator import validate_email, EmailNotValidError
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
from models.contactform import ContactForm
|
||||||
|
from schemas.contactform import ContactFormCreate, ContactFormSchema
|
||||||
|
|
||||||
|
def create_contact_form(db: Session, form_data: ContactFormCreate) -> ContactForm:
|
||||||
|
"""
|
||||||
|
Creates a new contact form submission 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 validate_contact_form_data(form_data: Dict[str, Any]) -> Dict[str, str]:
|
||||||
|
"""
|
||||||
|
Validates the contact form data against required fields and format rules.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
form_data (Dict[str, Any]): The raw contact form data to validate.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict[str, str]: A dictionary of validation errors, empty if validation passes.
|
||||||
|
"""
|
||||||
|
errors = {}
|
||||||
|
|
||||||
|
# Check for required fields
|
||||||
|
if not form_data.get("name"):
|
||||||
|
errors["name"] = "Name is required"
|
||||||
|
|
||||||
|
if not form_data.get("email"):
|
||||||
|
errors["email"] = "Email is required"
|
||||||
|
else:
|
||||||
|
# Validate email format
|
||||||
|
try:
|
||||||
|
validate_email(form_data["email"])
|
||||||
|
except EmailNotValidError:
|
||||||
|
errors["email"] = "Invalid email format"
|
||||||
|
|
||||||
|
if not form_data.get("message"):
|
||||||
|
errors["message"] = "Message is required"
|
||||||
|
|
||||||
|
return errors
|
||||||
|
|
||||||
|
def get_contact_form_by_id(db: Session, form_id: UUID) -> Optional[ContactForm]:
|
||||||
|
"""
|
||||||
|
Retrieves a contact form submission by its ID.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db (Session): The database session.
|
||||||
|
form_id (UUID): The ID of the contact form to retrieve.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[ContactForm]: The contact form object if found, otherwise None.
|
||||||
|
"""
|
||||||
|
return db.query(ContactForm).filter(ContactForm.id == form_id).first()
|
||||||
|
|
||||||
|
def format_validation_error_response(errors: Dict[str, str]) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Formats validation errors into a standardized response structure.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
errors (Dict[str, str]): Dictionary of field-specific validation errors.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict[str, Any]: A structured error response.
|
||||||
|
"""
|
||||||
|
return {
|
||||||
|
"status": "error",
|
||||||
|
"message": "Validation error",
|
||||||
|
"errors": errors
|
||||||
|
}
|
||||||
|
|
||||||
|
def send_notification_email(contact_form: ContactFormSchema) -> bool:
|
||||||
|
"""
|
||||||
|
Sends a notification email about the new contact form submission.
|
||||||
|
This is a placeholder for actual email sending implementation.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
contact_form (ContactFormSchema): The contact form data.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: True if the email was sent successfully, False otherwise.
|
||||||
|
"""
|
||||||
|
# This would be implemented with an actual email sending library
|
||||||
|
# like smtplib, sendgrid, etc.
|
||||||
|
# For now, just return True to simulate successful sending
|
||||||
|
return True
|
20
models/contact_form.py
Normal file
20
models/contact_form.py
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
from sqlalchemy import Column, String, DateTime, Text
|
||||||
|
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)
|
||||||
|
|
||||||
|
# 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())
|
35
schemas/contact_form.py
Normal file
35
schemas/contact_form.py
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
from pydantic import BaseModel, Field, EmailStr
|
||||||
|
from typing import Optional
|
||||||
|
from datetime import datetime
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
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")
|
||||||
|
|
||||||
|
class ContactFormCreate(ContactFormBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
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")
|
||||||
|
|
||||||
|
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": "Hello, I'd like to inquire 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