Django's cbv

Django's cbv
As we have learned, Django view function has two write written: cbv and fbv. cbv promote the use of class to write, fbv use the function to
write. Of course, to repeat lines of code, more official recommended cbv.
When writing cbv, written class class view, and then call the class of as_view () function in the url, had always thought that as long as the call up
with, and is not to understand the meaning. Of course fbv function can be executed directly. Today, we take a look at the source code cbv way.
As_view into the source code in PyCharm found that it is a classmethod.

Specific code omitted

def as_view(cls, **initkwargs):

Request-response procedure is the main entry point

...
DEF view (Request, * args, ** kwargs):
...
return self.dispatch (Request, * args, ** kwargs)
...
return view
can see it for internal use closures, returned view function, and view function returned a dispatch method. Then continues into the
dispatch method.

This code is not long

def dispatch(self, request, *args, **kwargs):

Try to find the right approach, if the method does not exist, error handling

If the method does not allow the request list or error handler.

request.method.lower IF () in self.http_method_names:
Handler = getattr (Self, request.method.lower (), self.http_method_not_allowed)
the else:
Handler = self.http_method_not_allowed
return Handler (Request, * args, ** kwargs)
Analyzing it can be seen that the request.method.lower () is in a list, this list is in the view of
http_method_names = [ 'get', ' post', 'put', 'patch', 'delete', ' head ',' options', ' trace']
method if the list, then the corresponding self removed. If not, then also enter the exception handler. This also explains cbv
the function name and http method high degree of overlap. Note getattr usage.
This is almost over. Tidy:
as_view () -> View () ->
dispatch () which mainly use the reflection principle. url mappings's about the principle (guess).
Summary: enter a request dispatch process, in the reflection type found get / post or the like, then the method returns the corresponding content back
to the dispatch, dispatch and the contents is then returned to the requester.
After the words: method can be implemented in a custom class dispatch method, and then call in the parent class. Before this can be achieved certain operations or after
work.

Guess you like

Origin www.cnblogs.com/abdm-989/p/11729557.html