feat: Generated endpoint endpoints/contact-us.post.py via AI for Contact_form
This commit is contained in:
parent
d041243c44
commit
d9ce088b5f
@ -0,0 +1,34 @@
|
|||||||
|
"""create table for contact_forms
|
||||||
|
|
||||||
|
Revision ID: 2a77b4cdd3e5
|
||||||
|
Revises: 0001
|
||||||
|
Create Date: 2023-05-25 12:37:51.615899
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '2a77b4cdd3e5'
|
||||||
|
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, default=lambda: str(uuid.uuid4())),
|
||||||
|
sa.Column('name', sa.String(), nullable=False),
|
||||||
|
sa.Column('email', sa.String(), nullable=False),
|
||||||
|
sa.Column('subject', sa.String(), nullable=False),
|
||||||
|
sa.Column('message', sa.Text(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(), server_default=func.now()),
|
||||||
|
sa.Column('updated_at', sa.DateTime(), server_default=func.now(), onupdate=func.now())
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
op.drop_table('contact_forms')
|
@ -0,0 +1,15 @@
|
|||||||
|
from fastapi import APIRouter, HTTPException, status
|
||||||
|
from schemas.contact_form import ContactFormCreate, ContactFormSchema
|
||||||
|
from helpers.contact_form_helpers import create_contact_form, validate_contact_form_data
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
@router.post("/contact-us", status_code=status.HTTP_201_CREATED, response_model=ContactFormSchema)
|
||||||
|
async def create_new_contact_form(contact_form_data: ContactFormCreate):
|
||||||
|
"""Create a new contact form"""
|
||||||
|
try:
|
||||||
|
validate_contact_form_data(contact_form_data)
|
||||||
|
new_contact_form = create_contact_form(contact_form_data=contact_form_data)
|
||||||
|
return new_contact_form
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
90
helpers/contact_form_helpers.py
Normal file
90
helpers/contact_form_helpers.py
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
from typing import List, Optional
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
import re
|
||||||
|
from models.contact_form import ContactForm
|
||||||
|
from schemas.contact_form import ContactFormCreate, ContactFormUpdate, ContactFormSchema
|
||||||
|
|
||||||
|
def get_contact_forms(db: Session) -> List[ContactFormSchema]:
|
||||||
|
"""
|
||||||
|
Retrieves all contact forms from the database.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db (Session): The database session.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List[ContactFormSchema]: A list of all contact form objects.
|
||||||
|
"""
|
||||||
|
return db.query(ContactForm).all()
|
||||||
|
|
||||||
|
def get_contact_form_by_id(db: Session, contact_form_id: str) -> Optional[ContactFormSchema]:
|
||||||
|
"""
|
||||||
|
Retrieves a single contact form by its ID.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db (Session): The database session.
|
||||||
|
contact_form_id (str): The ID of the contact form to retrieve.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[ContactFormSchema]: The contact form object if found, otherwise None.
|
||||||
|
"""
|
||||||
|
return db.query(ContactForm).filter(ContactForm.id == contact_form_id).first()
|
||||||
|
|
||||||
|
def create_contact_form(db: Session, contact_form_data: ContactFormCreate) -> ContactFormSchema:
|
||||||
|
"""
|
||||||
|
Creates a new contact form in the database.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db (Session): The database session.
|
||||||
|
contact_form_data (ContactFormCreate): The data for the contact form to create.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
ContactFormSchema: The newly created contact form object.
|
||||||
|
"""
|
||||||
|
validate_contact_form_data(contact_form_data)
|
||||||
|
db_contact_form = ContactForm(**contact_form_data.dict())
|
||||||
|
db.add(db_contact_form)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_contact_form)
|
||||||
|
return db_contact_form
|
||||||
|
|
||||||
|
def update_contact_form(db: Session, contact_form_id: str, contact_form_data: ContactFormUpdate) -> Optional[ContactFormSchema]:
|
||||||
|
"""
|
||||||
|
Updates an existing contact form in the database.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db (Session): The database session.
|
||||||
|
contact_form_id (str): The ID of the contact form to update.
|
||||||
|
contact_form_data (ContactFormUpdate): The updated data for the contact form.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[ContactFormSchema]: The updated contact form object if found, otherwise None.
|
||||||
|
"""
|
||||||
|
db_contact_form = db.query(ContactForm).filter(ContactForm.id == contact_form_id).first()
|
||||||
|
if not db_contact_form:
|
||||||
|
return None
|
||||||
|
validate_contact_form_data(contact_form_data)
|
||||||
|
update_data = contact_form_data.dict(exclude_unset=True)
|
||||||
|
for key, value in update_data.items():
|
||||||
|
setattr(db_contact_form, key, value)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_contact_form)
|
||||||
|
return db_contact_form
|
||||||
|
|
||||||
|
def validate_contact_form_data(contact_form_data: ContactFormCreate):
|
||||||
|
"""
|
||||||
|
Validates the contact form data.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
contact_form_data (ContactFormCreate): The contact form data to validate.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: If any of the validation rules are violated.
|
||||||
|
"""
|
||||||
|
if not contact_form_data.name or len(contact_form_data.name) < 3:
|
||||||
|
raise ValueError("Name must be at least 3 characters long.")
|
||||||
|
if not re.match(r"^[\w\.-]+@[\w\.-]+\.\w+$", contact_form_data.email):
|
||||||
|
raise ValueError("Invalid email address.")
|
||||||
|
if not contact_form_data.subject or len(contact_form_data.subject) < 5:
|
||||||
|
raise ValueError("Subject must be at least 5 characters long.")
|
||||||
|
if not contact_form_data.message or len(contact_form_data.message) < 10:
|
||||||
|
raise ValueError("Message must be at least 10 characters long.")
|
16
models/contact_form.py
Normal file
16
models/contact_form.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 ContactForm(Base):
|
||||||
|
__tablename__ = "contact_forms"
|
||||||
|
|
||||||
|
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||||
|
name = Column(String, nullable=False)
|
||||||
|
email = Column(String, nullable=False)
|
||||||
|
subject = Column(String, nullable=False)
|
||||||
|
message = Column(Text, nullable=False)
|
||||||
|
created_at = Column(DateTime, default=func.now())
|
||||||
|
updated_at = Column(DateTime, default=func.now(), onupdate=func.now())
|
27
schemas/contact_form.py
Normal file
27
schemas/contact_form.py
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
from pydantic import BaseModel, Field, EmailStr
|
||||||
|
from typing import Optional
|
||||||
|
from datetime import datetime
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
class ContactFormBase(BaseModel):
|
||||||
|
name: str = Field(..., min_length=1, description="Name of the person submitting the form")
|
||||||
|
email: EmailStr = Field(..., description="Email address of the person submitting the form")
|
||||||
|
subject: str = Field(..., min_length=1, description="Subject of the contact form")
|
||||||
|
message: str = Field(..., min_length=1, description="Message content of the contact form")
|
||||||
|
|
||||||
|
class ContactFormCreate(ContactFormBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class ContactFormUpdate(ContactFormBase):
|
||||||
|
name: Optional[str] = Field(None, min_length=1, description="Name of the person submitting the form")
|
||||||
|
email: Optional[EmailStr] = Field(None, description="Email address of the person submitting the form")
|
||||||
|
subject: Optional[str] = Field(None, min_length=1, description="Subject of the contact form")
|
||||||
|
message: Optional[str] = Field(None, min_length=1, description="Message content of the contact form")
|
||||||
|
|
||||||
|
class ContactFormSchema(ContactFormBase):
|
||||||
|
id: uuid.UUID
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
orm_mode = True
|
Loading…
x
Reference in New Issue
Block a user