

class CTRTrackMiddleware(object):

    def process_response(self, request, response):
        """
        CTR track middleware.
        :param request:
        :param response:
        :return:
        """
        if hasattr(request, 'ctr_track'):

            req = request.GET.dict()
            req.update(request.POST.dict())
            try:
                res = json.loads(response.content).get('data', {})
            except ValueError:
                res = {}

            for record in request.ctr_track:
                data = record.copy()

                try:
                    exposure_data = [
                        {'business_type': key, 'list_ids': value} for key, value in data.pop('data')(req, res).items()
                    ]
                except KeyError:
                    exposure_data = None  # response is broken

                if exposure_data:
                    data.update({
                        'is_exposure': 1,
                        'exposure_data': exposure_data
                    })

                for key, value in data.items():
                    try:
                        v = value(req, res) if callable(value) else value
                        data.update({key: v})
                    except KeyError:
                        # json response broken
                        pass

                request.logger.app(**data)

        return response
