✨ feat: Add new endpoints/email.post.py endpoint for Contact_form 🚀 📦 with updated dependencies
This commit is contained in:
parent
ea1e9f0833
commit
2608d9d0fa
@ -0,0 +1,32 @@
|
|||||||
|
"""initial creation of contact_forms table
|
||||||
|
Revision ID: 2a1c3d5e7f9b
|
||||||
|
Revises: 0001
|
||||||
|
Create Date: 2023-11-15 12:00:00.000000
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '2a1c3d5e7f9b'
|
||||||
|
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,36 @@
|
|||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from core.database import get_db
|
||||||
|
from schemas.contact_form import ContactFormCreate, ContactFormSchema
|
||||||
|
from helpers.contact_form_helpers import create_contact_form, validate_contact_form_data
|
||||||
|
|
||||||
|
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 the contact form data
|
||||||
|
errors = validate_contact_form_data({
|
||||||
|
"name": contact_form.name,
|
||||||
|
"email": contact_form.email,
|
||||||
|
"message": contact_form.message
|
||||||
|
})
|
||||||
|
|
||||||
|
# If there are validation errors, return a 400 response with the error details
|
||||||
|
if errors:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_400_BAD_REQUEST,
|
||||||
|
detail=errors
|
||||||
|
)
|
||||||
|
|
||||||
|
# Create the contact form in the database
|
||||||
|
new_contact_form = create_contact_form(db=db, contact_form_data=contact_form)
|
||||||
|
|
||||||
|
return new_contact_form
|
103
helpers/contact_form_helpers.py
Normal file
103
helpers/contact_form_helpers.py
Normal file
@ -0,0 +1,103 @@
|
|||||||
|
from typing import Optional, Dict, Any
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from email_validator import validate_email, EmailNotValidError
|
||||||
|
from models.contact_form import ContactForm
|
||||||
|
from schemas.contact_form import ContactFormCreate
|
||||||
|
|
||||||
|
def create_contact_form(db: Session, contact_form_data: ContactFormCreate) -> ContactForm:
|
||||||
|
"""
|
||||||
|
Creates a new contact form submission in the database after validating inputs.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db (Session): The database session.
|
||||||
|
contact_form_data (ContactFormCreate): The data for the contact form to create.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
ContactForm: The newly created contact form object.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
HTTPException: If any required field is missing or invalid.
|
||||||
|
"""
|
||||||
|
# Create a new contact form instance
|
||||||
|
db_contact_form = ContactForm(
|
||||||
|
name=contact_form_data.name,
|
||||||
|
email=contact_form_data.email,
|
||||||
|
message=contact_form_data.message
|
||||||
|
)
|
||||||
|
|
||||||
|
# Add to database, commit, and refresh
|
||||||
|
db.add(db_contact_form)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_contact_form)
|
||||||
|
|
||||||
|
return db_contact_form
|
||||||
|
|
||||||
|
def validate_contact_form_data(data: Dict[str, Any]) -> Dict[str, str]:
|
||||||
|
"""
|
||||||
|
Validates contact form data manually, checking for required fields and valid email format.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
data (Dict[str, Any]): The contact form data to validate.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict[str, str]: A dictionary of validation errors, empty if validation passes.
|
||||||
|
"""
|
||||||
|
errors = {}
|
||||||
|
|
||||||
|
# Check required fields
|
||||||
|
if not data.get("name"):
|
||||||
|
errors["name"] = "Name is required"
|
||||||
|
|
||||||
|
if not data.get("email"):
|
||||||
|
errors["email"] = "Email is required"
|
||||||
|
elif data.get("email"):
|
||||||
|
try:
|
||||||
|
# Validate email format using email_validator package
|
||||||
|
validate_email(data["email"])
|
||||||
|
except EmailNotValidError:
|
||||||
|
errors["email"] = "Email format is invalid"
|
||||||
|
|
||||||
|
if not data.get("message"):
|
||||||
|
errors["message"] = "Message is required"
|
||||||
|
|
||||||
|
return errors
|
||||||
|
|
||||||
|
def get_contact_form_by_id(db: Session, contact_form_id: str) -> Optional[ContactForm]:
|
||||||
|
"""
|
||||||
|
Retrieves a contact form submission by its ID.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db (Session): The database session.
|
||||||
|
contact_form_id (str): 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 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).offset(skip).limit(limit).all()
|
||||||
|
|
||||||
|
def get_contact_forms_by_email(db: Session, email: str) -> list[ContactForm]:
|
||||||
|
"""
|
||||||
|
Retrieves all contact form submissions from a specific email address.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db (Session): The database session.
|
||||||
|
email (str): The email address to filter by.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
list[ContactForm]: A list of contact form objects from the specified email.
|
||||||
|
"""
|
||||||
|
return db.query(ContactForm).filter(ContactForm.email == email).all()
|
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
|
python-dotenv>=0.19.0
|
||||||
bcrypt>=3.2.0
|
bcrypt>=3.2.0
|
||||||
alembic>=1.13.1
|
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, used for inheritance
|
||||||
|
class ContactFormBase(BaseModel):
|
||||||
|
name: str = Field(..., description="Contact person's name")
|
||||||
|
email: EmailStr = Field(..., description="Contact person's email address")
|
||||||
|
message: str = Field(..., description="Message content")
|
||||||
|
|
||||||
|
# Schema for creating a new ContactForm
|
||||||
|
class ContactFormCreate(ContactFormBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Schema for updating an existing ContactForm (all fields optional)
|
||||||
|
class ContactFormUpdate(BaseModel):
|
||||||
|
name: Optional[str] = Field(None, description="Contact person's name")
|
||||||
|
email: Optional[EmailStr] = Field(None, description="Contact person's email address")
|
||||||
|
message: Optional[str] = Field(None, description="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 more information 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