1. Curtis Maloney
  2. session-cart


session-cart / session_cart / middleware.py

from session_cart.utils import get_carts

class CartMiddleware(object):
    Middleware that handles adding session carts to the request object.


    def process_request(self, request):
        Add the carts to the request object. 
        request.carts = object()
        for name, Cart in get_carts().items():
            setattr(request.carts, name, Cart(request))
        if 'default' in get_carts():
            request.cart = property(lambda self: self.carts.default)

    def process_response(self, request, response):
        Update the session carts if they have changed.

        # Don't assume the request object has carts, another layer may have
        # returned request this middleware's process_request was called.
        if hasattr(request, 'carts'):
            for name in get_carts():
                getattr(request.carts, name).save()
        return response