Django class based views - request, args and kwargs objects

女生的网名这么多〃 提交于 2019-12-11 01:54:09

问题


It seems to me that in Django's generic class-based views, the parameters request, args and kwargs travel from method to method, both as view instance attributes, as well as method arguments.

What do I mean exactly?

Class django.views.generic.base.View, defines the following function, called by its as_view method:

def view(request, *args, **kwargs):
    self = cls(**initkwargs)
    if hasattr(self, 'get') and not hasattr(self, 'head'):
        self.head = self.get
    self.request = request
    self.args = args
    self.kwargs = kwargs
    return self.dispatch(request, *args, **kwargs)     

This function first sets request, args and kwargs as view instance attributes, and then invokes the view's dispatch method with all these as arguments. What exactly is the purpose of this, if any? Isn't it redundant?


回答1:


Although some CBV methods (like dispatch()) have the arguments passed to them directly, others do not. And, of course, you might want to define your own methods that have access to these values without having to pass them around.

Part of the point of CBVs is that you don't have to think as much about the flow of control (who is calling what); instead, you can just override small bits of functionality (e.g. get_context_data()). So it's more natural to think of data attached to the object rather than arguments that are passed around from method to method.

Why not get rid of the arguments entirely? Probably because it's a better match to the legacy of function-based views. For example, many FBVs will have a CBV equivalent that uses the exact same code in the get() method.



来源:https://stackoverflow.com/questions/21383063/django-class-based-views-request-args-and-kwargs-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!