Preface
Everyone knows that learning Django is actually very simple, and you can get started without spending much effort. Configure a url, assign it to a function to process it, and return a response, and there is almost nothing difficult to understand.
After writing too much, I gradually realized some problems. For example, there is a view that is more complicated and calls many other functions. What should I do if I want to encapsulate these functions? Of course, you can use the comment #-----view------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Python is an object-oriented programming language. If you only use functions to develop, you will miss out on many object-oriented advantages (inheritance, encapsulation, polymorphism). So Django later added Class-Based-View. Let's write a View in a class. The advantages of doing this are mainly as follows:
- Improves code reusability and can use object-oriented technologies such as Mixin (multiple inheritance)
- Different functions can be used to handle different HTTP methods, instead of using many if judgments to improve code readability
Using class-based views
If we want to write a view that handles GET methods, the following is what we write with a function.
from import HttpResponse def my_view(request): if == 'GET': # <view logic> return HttpResponse('result')
If you write it in class-based view, it is the following.
from import HttpResponse from import View class MyView(View): def get(self, request): # <view logic> return HttpResponse('result')
Django's url is to assign a request to a callable function, not a class. To address this problem, the class-based view provides aas_view()
A static method (that is, a class method), calling this method will create an instance of the class and then call it through the instance.dispatch()
method,dispatch()
The method will call the corresponding method according to the different method of the request to process the request (such asget()
, post()
wait). At this point, these methods are almost the same as function-based view. To receive a request, you will get a response to return. If the method is not defined, an HttpResponseNotAllowed exception will be thrown.
In the url, just write:
# from import url from import MyView urlpatterns = [ url(r'^about/$', MyView.as_view()), ]
The properties of a class can be set through two methods. The first is a common Python method, which can be overwritten by subclasses.
from import HttpResponse from import View class GreetingView(View): greeting = "Good Day" def get(self, request): return HttpResponse() # You can override that in a subclass class MorningGreetingView(GreetingView): greeting = "Morning to ya"
In the second method, you can also specify the properties of the class in the url:
Set the properties of the class in url Python
urlpatterns = [ url(r'^about/$', GreetingView.as_view(greeting="G'day")), ]
Using Mixin
I think to understand django's class-based-view (hereinafter referred to as cbv), we must first understand what the purpose of django's introduction of cbv. Before django1.3, generic view, which is the so-called general view, used function-based-view (fbv), that is, function-based view. Some people think fbv is more pythonic than cbv, but they think it is not. An important feature of python is object orientation. CBV can better reflect python object-oriented. cbv implements view methods through class. Compared with function, class can make use of polymorphic specificity, so it is easier to abstract the more general functions in the project from a macro level. I won’t explain much about polymorphism, and those who are interested will use Google. In short, it can be understood that a thing has multiple forms (characteristics). The implementation principle of cbv is easy to understand by looking at the source code of django. It is basically routed from the url to this cbv, and distributed through the dispatch method inside the cbv, distributing the get request to the method for processing, and distributing the post request to the method for processing. Other methods are similar. How to use polymorphism? The concept of mixin is introduced in cbv. Mixin is some basic classes that have been written, and then it will be combined into the ultimate desired class through different Mixins.
Therefore, the basis of understanding cbv is to understand Mixin. Mixin is used in Django to reuse code. A View Class can inherit multiple Mixins, but can only inherit one View (including a subclass of the View). It is recommended to write the View on the rightmost and multiple Mixins on the left. Mixin is also a relatively complex technology. I won’t go into details in this article. I will write an article about Mixin in the future.
Using a decorator
In CBV, method_decorator can be used to decorate the method.
from import login_required from import method_decorator from import TemplateView class ProtectedView(TemplateView): template_name = '' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(ProtectedView, self).dispatch(*args, **kwargs)
It can also be written on the class and pass the name of the method.
@method_decorator(login_required, name='dispatch') class ProtectedView(TemplateView): template_name = ''
If there are multiple decorators to decorate a method, you can write it as a list. For example, the following two writing methods are equivalent.
decorators = [never_cache, login_required] @method_decorator(decorators, name='dispatch') class ProtectedView(TemplateView): template_name = '' @method_decorator(never_cache, name='dispatch') @method_decorator(login_required, name='dispatch') class ProtectedView(TemplateView): template_name = ''
Summarize
The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate.