feat: Generated endpoint endpoints/email.post.py via AI for Contact_form and updated requirements.txt
This commit is contained in:
parent
e5fbd9e951
commit
e2b439996a
@ -0,0 +1,32 @@
|
||||
"""Initial creation for ContactForm
|
||||
Revision ID: 0a7b2c3d4e5f
|
||||
Revises: 0001
|
||||
Create Date: 2023-11-08 12:34:56.789012
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '0a7b2c3d4e5f'
|
||||
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,39 @@
|
||||
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 create_contact_form, validate_contact_form_data, send_notification_email
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/email", status_code=status.HTTP_201_CREATED, response_model=ContactFormSchema)
|
||||
async def submit_contact_form(
|
||||
contact_form: ContactFormCreate,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Submit a contact form with name, email, and message.
|
||||
All fields are required and email must be in valid format.
|
||||
"""
|
||||
# Validate form data
|
||||
errors = validate_contact_form_data(
|
||||
name=contact_form.name,
|
||||
email=contact_form.email,
|
||||
message=contact_form.message
|
||||
)
|
||||
|
||||
# If validation errors exist, return 400 with specific error messages
|
||||
if errors:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=errors
|
||||
)
|
||||
|
||||
# Create the contact form in the database
|
||||
db_contact_form = create_contact_form(db=db, contact_form=contact_form)
|
||||
|
||||
# Send notification email (this could be moved to a background task)
|
||||
send_notification_email(contact_form=db_contact_form)
|
||||
|
||||
return db_contact_form
|
108
helpers/contact_form_helpers.py
Normal file
108
helpers/contact_form_helpers.py
Normal file
@ -0,0 +1,108 @@
|
||||
from typing import Optional, List, Dict
|
||||
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, contact_form: ContactFormCreate) -> ContactForm:
|
||||
"""
|
||||
Creates a new contact form submission in the database.
|
||||
|
||||
Args:
|
||||
db (Session): The database session.
|
||||
contact_form (ContactFormCreate): The contact form data to create.
|
||||
|
||||
Returns:
|
||||
ContactForm: The newly created contact form object.
|
||||
"""
|
||||
db_contact_form = ContactForm(**contact_form.dict())
|
||||
db.add(db_contact_form)
|
||||
db.commit()
|
||||
db.refresh(db_contact_form)
|
||||
return db_contact_form
|
||||
|
||||
def validate_contact_form_data(name: str, email: str, message: str) -> Dict[str, str]:
|
||||
"""
|
||||
Validates contact form data fields.
|
||||
|
||||
Args:
|
||||
name (str): The name field to validate.
|
||||
email (str): The email field to validate.
|
||||
message (str): The message field to validate.
|
||||
|
||||
Returns:
|
||||
Dict[str, str]: Dictionary containing error messages if validation fails, empty if valid.
|
||||
"""
|
||||
errors = {}
|
||||
|
||||
# Validate name
|
||||
if not name or name.strip() == "":
|
||||
errors["name"] = "Name is required"
|
||||
|
||||
# Validate email
|
||||
if not email:
|
||||
errors["email"] = "Email is required"
|
||||
else:
|
||||
try:
|
||||
# Use email_validator to validate email format
|
||||
validate_email(email)
|
||||
except EmailNotValidError:
|
||||
errors["email"] = "Email is not valid"
|
||||
|
||||
# Validate message
|
||||
if not message or message.strip() == "":
|
||||
errors["message"] = "Message is required"
|
||||
|
||||
return errors
|
||||
|
||||
def get_all_contact_forms(db: Session, skip: int = 0, limit: int = 100) -> List[ContactForm]:
|
||||
"""
|
||||
Retrieves all contact form submissions with pagination.
|
||||
|
||||
Args:
|
||||
db (Session): The database session.
|
||||
skip (int, optional): Number of records to skip. Defaults to 0.
|
||||
limit (int, optional): Maximum number of records to return. Defaults to 100.
|
||||
|
||||
Returns:
|
||||
List[ContactForm]: A list of contact form objects.
|
||||
"""
|
||||
return db.query(ContactForm).order_by(ContactForm.created_at.desc()).offset(skip).limit(limit).all()
|
||||
|
||||
def get_contact_form_by_id(db: Session, contact_form_id: UUID) -> Optional[ContactForm]:
|
||||
"""
|
||||
Retrieves a single contact form submission by its ID.
|
||||
|
||||
Args:
|
||||
db (Session): The database session.
|
||||
contact_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 == contact_form_id).first()
|
||||
|
||||
def send_notification_email(contact_form: ContactFormSchema) -> bool:
|
||||
"""
|
||||
Sends a notification email when a new contact form is submitted.
|
||||
This is a placeholder function - implementation would depend on the email service being used.
|
||||
|
||||
Args:
|
||||
contact_form (ContactFormSchema): The contact form data.
|
||||
|
||||
Returns:
|
||||
bool: True if email was sent successfully, False otherwise.
|
||||
"""
|
||||
# This would be implemented with your email service of choice
|
||||
# For example, using SMTP, SendGrid, Mailgun, etc.
|
||||
|
||||
# Placeholder implementation
|
||||
try:
|
||||
# Code to send email would go here
|
||||
print(f"Notification email about contact from {contact_form.name} <{contact_form.email}> would be sent here")
|
||||
return True
|
||||
except Exception:
|
||||
# Log the error
|
||||
return False
|
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)
|
||||
|
||||
# Required 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 with common fields
|
||||
class ContactFormBase(BaseModel):
|
||||
name: str = Field(..., description="Contact's name")
|
||||
email: EmailStr = Field(..., description="Contact's email address")
|
||||
message: str = Field(..., description="Contact message content")
|
||||
|
||||
# Schema for creating a new ContactForm submission
|
||||
class ContactFormCreate(ContactFormBase):
|
||||
pass
|
||||
|
||||
# Schema for updating an existing ContactForm (all fields optional)
|
||||
class ContactFormUpdate(BaseModel):
|
||||
name: Optional[str] = Field(None, description="Contact's name")
|
||||
email: Optional[EmailStr] = Field(None, description="Contact's email address")
|
||||
message: Optional[str] = Field(None, description="Contact message content")
|
||||
|
||||
# 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 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