简体   繁体   English

在所有方法之后调用函数 Django Rest Framework ModelViewSet

[英]Invoke function after all methods Django Rest Framework ModelViewSet

I would like to invoke a function after all methods in a ModelViewSet.我想在 ModelViewSet 中的所有方法之后调用一个函数。 The function itself will be used as an external event log.该函数本身将用作外部事件日志。 So the response from the views would not be modified.因此不会修改意见的响应。 I was not able to figureout how to achieve this.我无法弄清楚如何实现这一目标。 My ModelViewSet is a very basic one with serializer class and queryset defined.我的 ModelViewSet 是一个非常基本的,定义了序列化器类和查询集。

Any help would be appreciated.任何帮助,将不胜感激。

You can always override any python class.您始终可以覆盖任何 python 类。 Overriding all the method can be little trickier and I guess will just create unnecessary logs.覆盖所有方法可能有点棘手,我想只会创建不必要的日志。 You should only override the method that is really of importance.您应该只覆盖真正重要的方法。 Here is an example:下面是一个例子:

class LoggingModelViewSet(viewsets.ModelViewSet):
    def perform_create(self, serializer):
        print('Invoked perform_create')
        serializer.save(owner=self.request.user)

    def finalize_response(self, request, response, *args, **kwargs):
        xresponse = super().finalize_response(request, response, *args, **kwargs)

        print('finalize_response', xresponse)
        return xresponse

and more like this... you should see the source here https://github.com/encode/django-rest-framework/blob/master/rest_framework/viewsets.py#L217 It is not so tricky.更像这样......你应该在这里看到源https://github.com/encode/django-rest-framework/blob/master/rest_framework/viewsets.py#L217这不是那么棘手。

Override the dispatch method of view.覆盖视图的dispatch方法。

class MyDRFView(...):

    def my_custom_logging_method(self, request, response, *args, **kwargs):
        # do something useful here.....
        ...

    def dispatch(self, request, *args, **kwargs):
        response = super().dispatch(request, *args, **kwargs)
        self.my_custom_logging_method(request, response, *args, **kwargs)
        return respons

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM