2

我敢肯定,关于 python 中的类型层次结构和初始化,我肯定有一些我不了解的东西......我想用 django rest 框架记录帖子正文,就像在 stackoverflow 上建议的那样:通过覆盖初始和 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调用时设置了用户。

现在,我求助于覆盖get然后post记录帖子正文的内容,但我不明白为什么当我覆盖该方法时未设置用户属性。

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

4

2 回答 2

1

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

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

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

于 2013-09-02T12:11:39.730 回答
0

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

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
于 2020-06-30T20:31:19.760 回答