1, Class view
1. Using the class view, different request modes corresponding to the view can be defined differently by different methods in the class. As follows:
from django.views.generic import View class RegisterView(View): """Class view: processing registration""" def get(self, request): """handle GET Request, return to the registration page""" return render(request, 'register.html') def post(self, request): """handle POST Request to implement the registration logic""" return HttpResponse('The registration logic is implemented here')
2. When configuring routing, use the as of class view_ View () method to add:
urlpatterns = [ # View functions: registering # url(r'^register/$', views.register, name='register'), # Class view: registering url(r'^register/$', views.RegisterView.as_view(), name='register'), ]
3. Class view principle
@classonlymethod def as_view(cls, **initkwargs): """ Main entry point for a request-response process. """ ...Omit code... 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 # Call the dispatch method and call different request methods according to different request methods return self.dispatch(request, *args, **kwargs) ...Omit code... # Return to the real function view return view
4. Use decorators in class views
def my_decorator(func): def wrapper(request, *args, **kwargs): print('Custom decorator called') print('Request path%s' % request.path) return func(request, *args, **kwargs) return wrapper class DemoView(View): def get(self, request): print('get method') return HttpResponse('ok') def post(self, request): print('post method') return HttpResponse('ok')
Decoration in URL configuration
urlpatterns = [ url(r'^demo/$', my_decorate(DemoView.as_view())) ]
Decoration in class view
When using the decorator prepared for the function view in the class view, you can't add the decorator directly. You need to use method_ The decorator converts it into a decorator for class view methods.
method_ The decorator decorator uses the name parameter to indicate the decorated method
# Add decorator for all request methods @method_decorator(my_decorator, name='dispatch') class DemoView(View): def get(self, request): print('get method') return HttpResponse('ok') def post(self, request): print('post method') return HttpResponse('ok') # Add decorators for specific request methods @method_decorator(my_decorator, name='get') class DemoView(View): def get(self, request): print('get method') return HttpResponse('ok') def post(self, request): print('post method') return HttpResponse('ok')
If you need to add decorators for multiple methods of the class view, but not all methods (refer to the above example for adding decorators for all methods), you can directly use method on the method that needs to add decorators_ Decorator, as shown below
from django.utils.decorators import method_decorator # Add decorators for specific request methods class DemoView(View): @method_decorator(my_decorator) # Added decorator for get method def get(self, request): print('get method') return HttpResponse('ok') @method_decorator(my_decorator) # A decorator has been added to the post method def post(self, request): print('post method') return HttpResponse('ok') def put(self, request): # No decorator was added for the put method print('put method') return HttpResponse('ok')
2, Middleware
1. Definition method of Middleware
Define a middleware factory function, and then return a middleware that can not be called. The middleware factory function needs to receive a get that can be called_ Response object. The returned middleware is also an object that can be called, and like the view, it needs to receive a request object parameter and return a response object.
def simple_middleware(get_response): # The code written here is executed only once when Django is first configured and initialized. def middleware(request): # The code written here is called before each request processing view. response = get_response(request) # The code written here is called after each request processing view. return response return middleware
For example, create a middleware.py file in the users application,
def my_middleware(get_response): print('init Called') def middleware(request): print('before request Called') response = get_response(request) print('after response Called') return response return middleware
After defining the middleware, you need to add the registered Middleware in the settings.py file
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'users.middleware.my_middleware', # Add Middleware ]
Execution sequence of multiple middleware: before the request view is processed, the middleware is executed from top to bottom. After the request view is processed, the middleware is executed from bottom to top. The init method is executed from bottom to top