Source code for app.pydantic_models
from pydantic import BaseModel, Field, field_validator
[docs]
class Product(BaseModel):
id: int
name: str
price: float = Field(ge=0)
stock: int = Field(ge=0)
reorder_threshold: int = Field(ge=0, default=5)
weight: float = Field(default=1.0, ge=0) # Weight in kg
[docs]
class CartItem(BaseModel):
product_id: int
quantity: int = Field(ge=1)
[docs]
class Cart(BaseModel):
id: str
items: dict[int, int] = Field(default_factory=dict)
[docs]
def add(self, product_id: int, quantity: int = 1) -> None:
self.items[product_id] = self.items.get(product_id, 0) + quantity
[docs]
def remove(self, product_id: int) -> None:
self.items.pop(product_id, None)
[docs]
def clear(self) -> None:
self.items.clear()
[docs]
class Order(BaseModel):
id: int
cart_id: str
items: list[CartItem]
total: float = 0.0
status: str = "created"
[docs]
@field_validator("status")
def valid_status(cls, v: str) -> str:
allowed = {"created", "paid", "packed", "shipped", "delivered", "cancelled"}
if v not in allowed:
raise ValueError("Invalid status")
return v