Update code in endpoints/customer.post.py

This commit is contained in:
Backend IM Bot 2025-03-25 13:01:46 +00:00
parent 03c73bfd0d
commit 5c95eb9e63

View File

@ -1,36 +1,69 @@
from fastapi import APIRouter, HTTPException
import uuid
customers = [] # In-memory storage
from sqlalchemy import create_engine, Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
router = APIRouter()
# Database configuration
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://user:password@localhost:5432/dbname")
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class Customer(Base):
__tablename__ = "customers"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
email = Column(String, unique=True, index=True)
phone = Column(String)
address = Column(String)
Base.metadata.create_all(bind=engine)
@router.post("/customer")
async def create_customer(
email: str = "customer@example.com",
name: str = "John Doe",
location: str = "New York",
gender: str = "male"
name: str,
email: str,
phone: str,
address: str
):
"""Create new customer endpoint"""
if any(c["email"] == email for c in customers):
raise HTTPException(status_code=400, detail="Email already exists")
db = SessionLocal()
customer_id = str(uuid.uuid4())
customers.append({
"id": customer_id,
"email": email,
"name": name,
"location": location,
"gender": gender
})
# Check if email already exists
if db.query(Customer).filter(Customer.email == email).first():
raise HTTPException(status_code=400, detail="Email already registered")
# Create new customer
customer = Customer(
name=name,
email=email,
phone=phone,
address=address
)
try:
db.add(customer)
db.commit()
db.refresh(customer)
except Exception as e:
db.rollback()
raise HTTPException(status_code=400, detail=str(e))
finally:
db.close()
return {
"message": "Customer created successfully",
"customer_id": customer_id,
"email": email,
"customer_id": customer.id,
"name": customer.name,
"method": "POST",
"_verb": "post",
"next_steps": [
"Complete customer profile",
"Add payment method"
"Customer verification",
"Complete profile"
]
}