我敢肯定,关于 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
记录帖子正文的内容,但我不明白为什么当我覆盖该方法时未设置用户属性。
非常感谢您对此事的任何澄清。