python - django源碼探究,as_view()的具體分發過程?
問題描述
最近在學習django的類視圖,就打開源碼學習下,但是對基類View的as_view方法不太理解,先把源碼貼上來:
@classonlymethod def as_view(cls, **initkwargs):'''Main entry point for a request-response process.'''for key in initkwargs: if key in cls.http_method_names:raise TypeError('You tried to pass in the %s method name as a ''keyword argument to %s(). Don’t do that.'% (key, cls.__name__)) if not hasattr(cls, key):raise TypeError('%s() received an invalid keyword %r. as_view ''only accepts arguments that are already ''attributes of the class.' % (cls.__name__, key))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)view.view_class = clsview.view_initkwargs = initkwargs# take name and docstring from classupdate_wrapper(view, cls, updated=())# and possible attributes set by decorators# like csrf_exempt from dispatchupdate_wrapper(view, cls.dispatch, assigned=())return view
因為最后涉及View的另外的一個方法dispatch,我也貼出這個方法源碼:
def dispatch(self, request, *args, **kwargs):# Try to dispatch to the right method; if a method doesn’t exist,# defer to the error handler. Also defer to the error handler if the# request method isn’t on the approved list.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_allowedreturn handler(request, *args, **kwargs)
當類視圖調用as_view方法時,會把請求時的request方法自動對應到相應的類方法上,比如request的get方法對應到類視圖的get方法。
但是我看完源碼的理解是:as_view僅僅能自動對應get和post(具體的request方法在類屬性當中有個列表:http_method_names = [’get’, ’post’, ’put’, ’patch’, ’delete’, ’head’, ’options’, ’trace’])等方法,如果我在類視圖定義了自己的方法,那as_view并不能把我自定義的方法對應起來。
但是,同樣是類視圖,ListView當中卻有get_queryset方法,那ListView在調用as_view方法時會自動調用這個get_queryset方法嗎(它并不是request的方法是吧?)?
代碼哪里提到了這個過程呢?
望大神指教~抱拳
問題解答
回答1:dispath方法里就是根據request的方法尋找class view對應的函數處理:handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
ListView中的get_queryset方法是別的函數調用的
