基于Django类的视图:扩展调度方法被认为是错误还是坏?

时间:2018-04-25 06:46:56

标签: python django class methods extends

在我们的django代码库中,我们扩展了调度方法,原因如下:

  1. 设置GET / POST方法共有的变量。
  2. 限制用户访问权限(为此创建了一个单独的mixin,只需扩展调度并进行检查)
  3. 如果它被认为是坏的,那为什么呢?又有什么选择?

1 个答案:

答案 0 :(得分:1)

您可以这样做,只要覆盖它是您获得所需功能的唯一选择。

例如,django-rest-framework会覆盖dispatch方法,以提供authenticationpermissionthrottling等功能。

请参阅here

    def dispatch(self, request, *args, **kwargs):
        """
        `.dispatch()` is pretty much the same as Django's regular dispatch,
        but with extra hooks for startup, finalize, and exception handling.
        """
        self.args = args
        self.kwargs = kwargs
        request = self.initialize_request(request, *args, **kwargs)
        self.request = request
        self.headers = self.default_response_headers  # deprecate?

        try:
            self.initial(request, *args, **kwargs)

            # Get the appropriate handler method
            if request.method.lower() in self.http_method_names:
                handler = getattr(self, request.method.lower(),
                                  self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed

            response = handler(request, *args, **kwargs)

        except Exception as exc:
            response = self.handle_exception(exc)

        self.response = self.finalize_response(request, response, *args, **kwargs)
        return self.response