如何在apiview中序列化响应对象?

时间:2016-02-23 10:34:48

标签: python django python-2.7 django-rest-framework

我正在开发一个中间件,它将在数据库表中记录用户发布,删除..

class APILogMiddleware(object):
"""
this middle ware will track all api actions
"""
def process_response(self, request, response):
    """
    """
    url = request.path
    try:
        if 'HTTP_X_FORWARDED_FOR' in request.META:
            ip_adds = request.META['HTTP_X_FORWARDED_FOR'].split(",")
            ip_address = ip_adds[0]
        else:
            ip_address = request.META['REMOTE_ADDR']

        user_id = request.user.id if request.user.is_authenticated() else None
        browser = request.META.get('HTTP_USER_AGENT', '')
        action = request.method
        # convert request.REQUEST to dict
        data = dict(request.REQUEST)
        if 'files' in data:
            data.pop("files", None)

        print data

        try:
            response_data = dict(response.data)


        except:
            response_data = {}
        if 'created_at' in response_data.keys():
            response_data.pop('created_at')
        # retrieve token http key
        try:
            token_string = request.META['HTTP_AUTHORIZATION']
            token_string = token_string.replace('Token', '').strip()
            token_string = token_string.replace('token', '').strip()
        except KeyError:
            token_string = None

        log_aok_api_action.apply_async((user_id, ip_address, browser, url, action, data, response_data,
                                        token_string), expires=60)
    except ConnectionError as e:
        pass
    return response

views.py

@api_view(('GET',))
def index(request, format=None):
    """ default index page """
    conf = dict()
    for k, v in settings.CONSTANCE_CONFIG.iteritems():
        # TODO: why not use getattr(config, k)?
        conf['%s' % k] = config.__getattr__('%s' % k)

    return Response({
        'status': 'up',
        'constance': conf,
        'countries': COUNTRIES,
        'currencies': CURRENCIES,
        'notification_settings_choices': NotificationSettings.NOTIFICATION_CHOICES

    })

当我转到主页时,我收到了一条错误消息,我尝试了json.dumps(response_data),并且它有效。 但当我做response_data_t = json.dumps(response_data) 然后我将json字符串传递给log_aok_api_action.apply_async它仍然给我同样的错误.Akkward。

<django.utils.functional.__proxy__ object at 0xb4d713ec> is not JSON serializable

models.py

class ApiLog(models.Model):
""" ApiLog
"""
user = models.BigIntegerField(_('User'), blank=True, null=True)
token = models.CharField(_('Token Key'), max_length=255, null=True, blank=True)
ip_address = models.IPAddressField()
browser = models.CharField(_('Browser'), max_length=256, null=True, blank=True)
url = models.CharField(_('URL'), max_length=256, null=True, blank=True)
action = models.CharField(_('Action'), max_length=100, null=True, blank=True)
data = JSONField(_('Data'), blank=True, null=True)
response_data = JSONField(_('Response Data'), blank=True, null=True)

country = models.CharField(_('Country'), max_length=100, null=True, blank=True)

created_at = models.DateTimeField(auto_now_add=True)

objects = ApiLogManager()

class Meta:
    app_label = 'extra'

@property
def username(self):
    return User.objects.get(id=self.user) if self.user else ''

def __str__(self):
    # Use django.utils.encoding.force_bytes() because value returned is unicode
    return force_bytes('user %s performed %s' % (self.user, self.action))

def __unicode__(self):
    return u'user %s performed %s' % (self.user, self.action)

0 个答案:

没有答案