feat: Generated endpoint endpoints/contact.post.py via AI for Contact and updated requirements.txt
This commit is contained in:
parent
8c81159394
commit
54d0f0a712
29
alembic/versions/20250415_171341_3fffd58c_update_contact.py
Normal file
29
alembic/versions/20250415_171341_3fffd58c_update_contact.py
Normal file
@ -0,0 +1,29 @@
|
||||
"""create contacts table
|
||||
Revision ID: 0002
|
||||
Revises: 0001
|
||||
Create Date: 2024-01-20 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,24 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, 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_input, validate_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_input(contact_data.dict())
|
||||
validation_errors = validate_contact_data(sanitized_data)
|
||||
|
||||
if validation_errors:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=validation_errors
|
||||
)
|
||||
|
||||
contact = create_contact(db=db, contact_data=ContactCreate(**sanitized_data))
|
||||
return format_contact_response(contact)
|
100
helpers/contact_helpers.py
Normal file
100
helpers/contact_helpers.py
Normal file
@ -0,0 +1,100 @@
|
||||
from typing import Dict, Any
|
||||
from sqlalchemy.orm import Session
|
||||
from models.contact import Contact
|
||||
from schemas.contact import ContactCreate, ContactSchema
|
||||
from fastapi import HTTPException, status
|
||||
from pydantic import EmailStr
|
||||
|
||||
def validate_contact_data(contact_data: Dict[str, Any]) -> Dict[str, str]:
|
||||
"""
|
||||
Validates contact form submission data.
|
||||
|
||||
Args:
|
||||
contact_data (Dict[str, Any]): The contact form data to validate.
|
||||
|
||||
Returns:
|
||||
Dict[str, str]: Dictionary of validation errors, empty if valid.
|
||||
"""
|
||||
errors = {}
|
||||
|
||||
# Check required fields
|
||||
if not contact_data.get("name"):
|
||||
errors["name"] = "Name is required"
|
||||
elif len(contact_data["name"].strip()) < 1:
|
||||
errors["name"] = "Name cannot be empty"
|
||||
|
||||
if not contact_data.get("email"):
|
||||
errors["email"] = "Email is required"
|
||||
elif not isinstance(contact_data["email"], EmailStr):
|
||||
errors["email"] = "Invalid email format"
|
||||
|
||||
if not contact_data.get("message"):
|
||||
errors["message"] = "Message is required"
|
||||
elif len(contact_data["message"].strip()) < 1:
|
||||
errors["message"] = "Message cannot be empty"
|
||||
|
||||
return errors
|
||||
|
||||
def create_contact(db: Session, contact_data: ContactCreate) -> Contact:
|
||||
"""
|
||||
Creates a new contact submission in the database.
|
||||
|
||||
Args:
|
||||
db (Session): The database session.
|
||||
contact_data (ContactCreate): The validated contact form data.
|
||||
|
||||
Returns:
|
||||
Contact: The newly created contact object.
|
||||
|
||||
Raises:
|
||||
HTTPException: If there are validation errors.
|
||||
"""
|
||||
# Validate data
|
||||
validation_errors = validate_contact_data(contact_data.dict())
|
||||
if validation_errors:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=validation_errors
|
||||
)
|
||||
|
||||
# Create new contact
|
||||
db_contact = Contact(**contact_data.dict())
|
||||
db.add(db_contact)
|
||||
db.commit()
|
||||
db.refresh(db_contact)
|
||||
return db_contact
|
||||
|
||||
def format_contact_response(contact: Contact) -> ContactSchema:
|
||||
"""
|
||||
Formats a contact database object into the response schema.
|
||||
|
||||
Args:
|
||||
contact (Contact): The contact database object.
|
||||
|
||||
Returns:
|
||||
ContactSchema: The formatted contact response.
|
||||
"""
|
||||
return ContactSchema.from_orm(contact)
|
||||
|
||||
def sanitize_contact_input(contact_data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Sanitizes contact form input data.
|
||||
|
||||
Args:
|
||||
contact_data (Dict[str, Any]): Raw contact form data.
|
||||
|
||||
Returns:
|
||||
Dict[str, Any]: Sanitized contact form data.
|
||||
"""
|
||||
sanitized = {}
|
||||
|
||||
if "name" in contact_data:
|
||||
sanitized["name"] = contact_data["name"].strip()
|
||||
|
||||
if "email" in contact_data:
|
||||
sanitized["email"] = contact_data["email"].lower().strip()
|
||||
|
||||
if "message" in contact_data:
|
||||
sanitized["message"] = contact_data["message"].strip()
|
||||
|
||||
return sanitized
|
15
models/contact.py
Normal file
15
models/contact.py
Normal file
@ -0,0 +1,15 @@
|
||||
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, 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, 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