Django休息框架覆盖自定义日志记录的初始化绕过OAuth初始化

时间:2013-09-02 11:26:34

标签: django django-rest-framework

我确信在python中必须存在一些我不了解的类型层次结构和初始化... 我想用django rest框架记录帖子主体,如建议的here on stackoverflow:通过覆盖initial和finalize_response。

这就是我的mixin的样子:

class LoggingMixin(object):
"""
Provides full logging of requests and responses
"""

def finalize_response(self, request, response, *args, **kwargs):
    # do the logging
    if settings.DEBUG:
        logger.debug("[{0}] {1}".format(self.__class__.__name__, response.data))
    return super(LoggingMixin, self).finalize_response(request, response, *args, **kwargs)

def initial(self, request, *args, **kwargs):
    # do the logging
    if settings.DEBUG:
        try:
            data = request._data
            logger.debug("[{0}] {1}".format(self.__class__.__name__, data))
        except exceptions.ParseError:
            data = '[Invalid data in request]'

    super(LoggingMixin, self).initial(self, request, *args, **kwargs)

我的观点:

class BulkScan(LoggingMixin, generics.ListCreateAPIView):
"""
Provides get (list all) and post (single) for scans.
"""
queryset = Scan.objects.all()
serializer_class = ScanSerializer
authentication_classes = (OAuth2Authentication,)
permission_classes = (IsAuthenticated,)

# insert the user on save
def pre_save(self, obj):
    for scan in obj:
        scan.user = self.request.user

def post(self, request, *args, **kwargs):
    serializer = ScanSerializer(data=request.DATA, many=True)
    if serializer.is_valid():
        self.pre_save(serializer.object)
        self.object = serializer.save(force_insert=True)
        self.post_save(self.object, created=True)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED,
                        headers=headers)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

然而,post或get请求失败,抱怨request.user属性不存在。这必须在那里自动注入。如果我没有覆盖initial那么一切都很好,并且在调用APIView.initial时设置用户。

现在,我使用覆盖getpost,然后记录帖子正文的内容,但是当我覆盖方法时,我不明白为什么没有设置用户属性。< / p>

非常感谢对此事的任何澄清。

2 个答案:

答案 0 :(得分:1)

你正在调用初始错误的超级实现。不要通过self

super(LoggingMixin, self).initial(request, *args, **kwargs)

希望能解决它 - 似乎没有其他任何错误。

答案 1 :(得分:0)

@ carlton-gibson是正确的,但还有另一件事。我有同样的问题。通过在进行日志记录之前调用super()的initial()来对其进行了修复。

def initial(self, request, *args, **kwargs):
    # do the logging
    result = super(LoggingMixin, self).initial(request, *args, **kwargs)
    if settings.DEBUG:
        try:
            data = request._data
            logger.debug("[{0}] {1}".format(self.__class__.__name__, data))
        except exceptions.ParseError:
            data = '[Invalid data in request]'
    return result