From 54d0f0a71249908b75342f54c45d59e9e15be1a4 Mon Sep 17 00:00:00 2001 From: Backend IM Bot Date: Tue, 15 Apr 2025 17:14:18 +0000 Subject: [PATCH] feat: Generated endpoint endpoints/contact.post.py via AI for Contact and updated requirements.txt --- ...20250415_171341_3fffd58c_update_contact.py | 29 +++++ endpoints/contact.post.py | 24 +++++ helpers/contact_helpers.py | 100 ++++++++++++++++++ models/contact.py | 15 +++ schemas/contact.py | 35 ++++++ 5 files changed, 203 insertions(+) create mode 100644 alembic/versions/20250415_171341_3fffd58c_update_contact.py create mode 100644 helpers/contact_helpers.py create mode 100644 models/contact.py create mode 100644 schemas/contact.py diff --git a/alembic/versions/20250415_171341_3fffd58c_update_contact.py b/alembic/versions/20250415_171341_3fffd58c_update_contact.py new file mode 100644 index 0000000..9e627b6 --- /dev/null +++ b/alembic/versions/20250415_171341_3fffd58c_update_contact.py @@ -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') \ No newline at end of file diff --git a/endpoints/contact.post.py b/endpoints/contact.post.py index e69de29..231f7af 100644 --- a/endpoints/contact.post.py +++ b/endpoints/contact.post.py @@ -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) \ No newline at end of file diff --git a/helpers/contact_helpers.py b/helpers/contact_helpers.py new file mode 100644 index 0000000..8c6259d --- /dev/null +++ b/helpers/contact_helpers.py @@ -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 \ No newline at end of file diff --git a/models/contact.py b/models/contact.py new file mode 100644 index 0000000..e41dd2c --- /dev/null +++ b/models/contact.py @@ -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()) \ No newline at end of file diff --git a/schemas/contact.py b/schemas/contact.py new file mode 100644 index 0000000..c1e4e34 --- /dev/null +++ b/schemas/contact.py @@ -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" + } + } \ No newline at end of file