如何覆盖Django通用基本View的调度方法?

问题描述 投票:1回答:1

如果我编写一个从Django通用基本View继承的类,重写其调度方法的正确方法是什么? documentation似乎表明它可以被覆盖,但是该示例并未确切显示该方法。

如果我这样做,

class MyView(View):
    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        response = dispatch(request, *args, **kwargs)
        return HttpResponse('Hello, world!')

Django说,

NameError: name 'dispatch' is not defined.

如果我随后将调度语句更改为此,

response = self.dispatch(request, *args, **kwargs)

Django说,

RecursionError: maximum recursion depth exceeded
django
1个回答
0
投票

文档似乎表明可以覆盖它,但是该示例并未确切显示该方法。

您可以覆盖所有方法(某些Python内置函数除外,但这在此不相关)。

但是,覆盖dispatch并不常见,因为dispatch基本上将请求的方法(GET,POST,PATCH,PUT,DELETE等)检查为对应的方法getpostpatchputdelete

因此,您发现,如果在dispatch()方法中call get()方法,则会出现相互递归的情况。这里dispatch将呼叫getget将呼叫dispatch。这样,它们将继续相互调用,直到调用堆栈耗尽为止。

[在某些情况下,视图会覆盖dispatch方法,例如LogoutView does this [GitHub]

LogoutView

此处class LogoutView(SuccessURLAllowedHostsMixin, TemplateView): # … @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): auth_logout(request) next_page = self.get_next_page() if next_page: # Redirect to this page until the session has been cleared. return HttpResponseRedirect(next_page) return super().dispatch(request, *args, **kwargs)方法将确保为给定用户进行dispatch调用。但是logout方法不会再次调用get方法。

© www.soinside.com 2019 - 2024. All rights reserved.