feat: Generated endpoint endpoints/contact.post.py via AI for Contact
This commit is contained in:
parent
b790f6be7c
commit
3b7de1cecd
29
alembic/versions/20250415_181502_db79e976_update_contact.py
Normal file
29
alembic/versions/20250415_181502_db79e976_update_contact.py
Normal file
@ -0,0 +1,29 @@
|
|||||||
|
"""create contacts table
|
||||||
|
Revision ID: 0002
|
||||||
|
Revises: 0001
|
||||||
|
Create Date: 2024-01-23 10:00:00.000000
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '0002'
|
||||||
|
down_revision = '0001'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
op.create_table(
|
||||||
|
'contacts',
|
||||||
|
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_contacts_email'), 'contacts', ['email'], unique=False)
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
op.drop_index(op.f('ix_contacts_email'), table_name='contacts')
|
||||||
|
op.drop_table('contacts')
|
@ -0,0 +1,16 @@
|
|||||||
|
from fastapi import APIRouter, Depends, status
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from core.database import get_db
|
||||||
|
from schemas.contact import ContactCreate, ContactSchema
|
||||||
|
from helpers.contact_helpers import create_contact, sanitize_contact_data, format_contact_response
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.post("/contact", status_code=status.HTTP_201_CREATED, response_model=ContactSchema)
|
||||||
|
async def create_contact_submission(
|
||||||
|
contact_data: ContactCreate,
|
||||||
|
db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
sanitized_data = sanitize_contact_data(contact_data)
|
||||||
|
contact = create_contact(db=db, contact_data=sanitized_data)
|
||||||
|
return format_contact_response(contact)
|
97
helpers/contact_helpers.py
Normal file
97
helpers/contact_helpers.py
Normal file
@ -0,0 +1,97 @@
|
|||||||
|
from typing import Dict
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from models.contact import Contact
|
||||||
|
from schemas.contact import ContactCreate, ContactSchema
|
||||||
|
|
||||||
|
def validate_contact_data(contact_data: ContactCreate) -> Dict[str, str]:
|
||||||
|
"""
|
||||||
|
Validates contact form submission data.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
contact_data (ContactCreate): The contact form data to validate.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict[str, str]: Dictionary containing validation errors, if any.
|
||||||
|
"""
|
||||||
|
errors = {}
|
||||||
|
|
||||||
|
# Check required fields
|
||||||
|
if not contact_data.name or not contact_data.name.strip():
|
||||||
|
errors["name"] = "Name is required"
|
||||||
|
elif len(contact_data.name) > 255:
|
||||||
|
errors["name"] = "Name must not exceed 255 characters"
|
||||||
|
|
||||||
|
if not contact_data.email:
|
||||||
|
errors["email"] = "Email is required"
|
||||||
|
|
||||||
|
if not contact_data.message or not contact_data.message.strip():
|
||||||
|
errors["message"] = "Message is required"
|
||||||
|
|
||||||
|
return errors
|
||||||
|
|
||||||
|
def create_contact(db: Session, contact_data: ContactCreate) -> Contact:
|
||||||
|
"""
|
||||||
|
Creates a new contact submission in the database after validation.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db (Session): The database session.
|
||||||
|
contact_data (ContactCreate): The validated contact form data.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Contact: The newly created contact object.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
HTTPException: If validation fails or database operation fails.
|
||||||
|
"""
|
||||||
|
# Validate contact data
|
||||||
|
validation_errors = validate_contact_data(contact_data)
|
||||||
|
if validation_errors:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail={"message": "Validation failed", "errors": validation_errors}
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Create new contact
|
||||||
|
db_contact = Contact(**contact_data.dict())
|
||||||
|
db.add(db_contact)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_contact)
|
||||||
|
return db_contact
|
||||||
|
except Exception as e:
|
||||||
|
db.rollback()
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=500,
|
||||||
|
detail={"message": "Failed to create contact", "error": str(e)}
|
||||||
|
)
|
||||||
|
|
||||||
|
def sanitize_contact_data(contact_data: ContactCreate) -> ContactCreate:
|
||||||
|
"""
|
||||||
|
Sanitizes contact form input data.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
contact_data (ContactCreate): The raw contact form data.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
ContactCreate: The sanitized contact form data.
|
||||||
|
"""
|
||||||
|
# Create a new dict with sanitized values
|
||||||
|
sanitized_data = ContactCreate(
|
||||||
|
name=contact_data.name.strip(),
|
||||||
|
email=contact_data.email.strip().lower(),
|
||||||
|
message=contact_data.message.strip()
|
||||||
|
)
|
||||||
|
return sanitized_data
|
||||||
|
|
||||||
|
def format_contact_response(contact: Contact) -> ContactSchema:
|
||||||
|
"""
|
||||||
|
Formats a contact database object into a response schema.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
contact (Contact): The contact database object.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
ContactSchema: The formatted contact response.
|
||||||
|
"""
|
||||||
|
return ContactSchema.from_orm(contact)
|
16
models/contact.py
Normal file
16
models/contact.py
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
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 Contact(Base):
|
||||||
|
__tablename__ = "contacts"
|
||||||
|
|
||||||
|
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||||
|
name = Column(String, nullable=False)
|
||||||
|
email = Column(String, nullable=False, index=True)
|
||||||
|
message = Column(Text, nullable=False)
|
||||||
|
|
||||||
|
created_at = Column(DateTime, default=func.now())
|
||||||
|
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
|
35
schemas/contact.py
Normal file
35
schemas/contact.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 ContactBase(BaseModel):
|
||||||
|
name: str = Field(..., min_length=1, max_length=255, description="Contact name")
|
||||||
|
email: EmailStr = Field(..., description="Contact email address")
|
||||||
|
message: str = Field(..., min_length=1, description="Contact message")
|
||||||
|
|
||||||
|
class ContactCreate(ContactBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class ContactUpdate(BaseModel):
|
||||||
|
name: Optional[str] = Field(None, min_length=1, max_length=255, description="Contact name")
|
||||||
|
email: Optional[EmailStr] = Field(None, description="Contact email address")
|
||||||
|
message: Optional[str] = Field(None, min_length=1, description="Contact message")
|
||||||
|
|
||||||
|
class ContactSchema(ContactBase):
|
||||||
|
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 would like to get in touch.",
|
||||||
|
"created_at": "2023-01-01T12:00:00",
|
||||||
|
"updated_at": "2023-01-01T12:00:00"
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user