我确信在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
时设置用户。
现在,我使用覆盖get
和post
,然后记录帖子正文的内容,但是当我覆盖方法时,我不明白为什么没有设置用户属性。< / p>
非常感谢对此事的任何澄清。
答案 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