Source code for app.cart

from app.pydantic_models import Cart


[docs] class CartManager: """ Manage shopping carts using the Singleton design pattern. """ _instance = None def __init__(self): """ Block direct instantiation. Raises: RuntimeError: If instantiated directly via the constructor, to force usage of get_instance(). """ raise RuntimeError("You cannot use the public constructor `get_instance()` instead") def _init(self): """ Initialize the manager with an empty cart store. """ self._carts: dict[str, Cart] = {}
[docs] @staticmethod def get_instance(): """ Return the unique CartManager instance, creating it if needed. Returns: CartManager: The singleton instance. """ if CartManager._instance is None: CartManager._instance = CartManager.__new__(CartManager) CartManager._instance._init() return CartManager._instance
[docs] def get_cart(self, cart_id: str = "default") -> Cart: """ Return an existing cart or create a new one. Args: cart_id: The unique cart identifier. Default value to "default". Returns: Cart: The cart matching the given identifier. """ if cart_id not in self._carts: self._carts[cart_id] = Cart(id=cart_id) return self._carts[cart_id]
[docs] def clear_cart(self, cart_id: str = "default") -> None: """ Clear the contents of a cart. Args: cart_id: The identifier of the cart to clear. Default value to "default". """ if cart_id in self._carts: self._carts[cart_id].items.clear()