from market.models import Market


class MarketMiddleware(object):
    
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        market = None
        user = getattr(request, 'user', None)
        if user.is_authenticated:
            try:
                market = Market.objects.get(user=user)
            except Market.MultipleObjectsReturned:
                market = Market.objects.filter(user=user)[0]
            except Market.DoesNotExist:
                market = None

        request.market = market
        return self.get_response(request)

