
Create a complete e-commerce application with the following features: - User authentication and authorization - Product and category management - Shopping cart functionality - Order processing - Database migrations with Alembic - Comprehensive documentation
60 lines
1.6 KiB
Python
60 lines
1.6 KiB
Python
import uuid
|
|
from typing import List, Optional
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models.product import Product
|
|
from app.schemas.product import ProductCreate, ProductUpdate
|
|
|
|
|
|
def get_by_id(db: Session, product_id: str) -> Optional[Product]:
|
|
return db.query(Product).filter(Product.id == product_id).first()
|
|
|
|
|
|
def get_multi(db: Session, *, skip: int = 0, limit: int = 100) -> List[Product]:
|
|
return db.query(Product).filter(Product.is_active).offset(skip).limit(limit).all()
|
|
|
|
|
|
def get_by_category(db: Session, *, category_id: str, skip: int = 0, limit: int = 100) -> List[Product]:
|
|
return db.query(Product).filter(
|
|
Product.category_id == category_id,
|
|
Product.is_active
|
|
).offset(skip).limit(limit).all()
|
|
|
|
|
|
def create(db: Session, *, obj_in: ProductCreate) -> Product:
|
|
db_obj = Product(
|
|
id=str(uuid.uuid4()),
|
|
name=obj_in.name,
|
|
description=obj_in.description,
|
|
price=obj_in.price,
|
|
stock=obj_in.stock,
|
|
is_active=obj_in.is_active,
|
|
category_id=obj_in.category_id,
|
|
image_url=obj_in.image_url,
|
|
)
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
|
|
def update(db: Session, *, db_obj: Product, obj_in: ProductUpdate) -> Product:
|
|
update_data = obj_in.dict(exclude_unset=True)
|
|
|
|
for field, value in update_data.items():
|
|
setattr(db_obj, field, value)
|
|
|
|
db.add(db_obj)
|
|
db.commit()
|
|
db.refresh(db_obj)
|
|
return db_obj
|
|
|
|
|
|
def delete(db: Session, *, product_id: str) -> Product:
|
|
obj = db.query(Product).get(product_id)
|
|
obj.is_active = False
|
|
db.add(obj)
|
|
db.commit()
|
|
db.refresh(obj)
|
|
return obj |