在我们的django代码库中,我们扩展了调度方法,原因如下:
如果它被认为是坏的,那为什么呢?又有什么选择?
答案 0 :(得分:1)
您可以这样做,只要覆盖它是您获得所需功能的唯一选择。
例如,django-rest-framework
会覆盖dispatch
方法,以提供authentication
,permission
,throttling
等功能。
请参阅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