1.django client request process
Before logging function, you need to get the user's sesssion, but each view function will be added decorators to check very unreasonable, the middleware can solve this problem
User client ---> WSGI (request object encapsulates) ---> intermediate (Hook frame) ---> Routing ---> views ---> models ---> db ---> template- - middleware ---> wsgi ---> client
2. What is the middleware
django middleware for processing the request and response frame hooks django level change in the input and output django globally, there are various types of middleware, the middleware can be completed for each specific function, execution may help us view additional operations before and after the completion of a function, essentially class
MIDDLEWARE settings in the configuration of middleware that information, but also a string classes, that is, a mezzanine, you can click to see class by import
3. Custom Middleware
5 kinds of middleware, the focus is on the parameters! Timing of execution! Execution order! Return value!
Essentially class, the class is defined under the previous five ways, have different roles in different execution timing!
process_request(self,request)
process_view(self,request,view_func,view_args,view_kwargs)
process_template_response(self,request,response)
process_exception(self,request,exception)
process_response(self,request,response)
1)process_request(self,request)
Parameters: request the return of the object wsgi
Execution time: (a request does not meet the requirements of the truncation) after receiving the request before execution
The execution order of: setting register in accordance with the order of execution, in order to come in register class in the implementation of this method in each class
return value:
When the return value is null None: url -> views
When you return the response object: direct return to the client
# # Middle / middles.py a class is a middleware can write more from django.utils.deprecation Import MiddlewareMixin from django.shortcuts Import the render, HttpResponse class MD1 (MiddlewareMixin): DEF process_request (Self, Request): Print ( ' MD1 process_request ' ) # return HttpResponse ( 'access Denied') # If you return it will be directly returned to the client # # settings.py registered MIDDLEWARE = [ ... ' middle.middles.MD1 ' , ... ]
2)process_response(self,request,response)
Parameters: request wsgi returned objects, response objects (view may be returned by the function, it may be returned process_request)
Execution timing: after the view function is executed, there may also be yes process_request return value after execution of the order
The execution order of: setting performed in reverse order of registration, obtaining process_response flashback method is performed in each class registration class
Returns: the object must return response
# # / Middle / middles.py write two middleware to view the execution order from django.utils.deprecation Import MiddlewareMixin from django.shortcuts Import the render, HttpResponse class MD1 (MiddlewareMixin): DEF process_request (Self, Request): Print ( ' MD1 process_request ' ) # return the HttpResponse (' access denied ') DEF process_response (Self, Request, Response): Print ( ' MDl process_response ' ) # return the HttpResponse (' access denied ') return Response class MD2 (MiddlewareMixin): DEF process_request (Self, Request): Print ( ' MD2 process_request ' ) # return the HttpResponse ( 'access denied') DEF process_response (Self, Request, Response): Print ( ' MD2 process_response ' ) # return the HttpResponse ( 'access denied') return Response # #settings two intermediate classes registered mIDDLEWARE = [ ... ' middle.middles.MD1 ' , ' middle.middles.MD2 ' , ... ]
3)process_view(self,request,view_func ,view_args, view_kwargs)
Parameters: wsgi to request object, view_func this matching function performs view, view_args position matching this view function parameters, view_kwargs view function key matching this parameter
Execution timing: the url matching rear view function to perform, and then execute the view function
Execution order: According to the order setting register
return value:
An empty return value: the normal process (process_request ---> url ---> process_view ---> views.py ---> process_response)
response object: Truncated Process (process_request ---> url ---> process_view (skip all methods view, all views and functions return directly response) -> process_response)
# # Middle / middles.py view has a return value, the results of observation from django.utils.deprecation Import MiddlewareMixin from django.shortcuts Import the render, the HttpResponse class MDl (MiddlewareMixin): DEF process_request (Self, Request): Print ( ' MDl process_request ' ) # return the HttpResponse (' access denied ') DEF process_response (Self, Request, Response): Print ( ' MDl process_response ' ) # return the HttpResponse (' access denied ') return Response def process_view(self, request, view_func, view_args, view_kwargs): print('MD1 process_view', view_func) return HttpResponse('test') class MD2(MiddlewareMixin): def process_request(self, request): print('MD2 process_request') # return HttpResponse('拒绝访问') def process_response(self, request, response): print('MD2 process_response') #return HttpResponse ( 'access denied') return Response DEF process_view (Self, Request, view_func, view_args, view_kwargs): Print ( ' MD2 process_view ' , view_func) # ## Results of MDl process_request MD2 process_request MDl process_view <function presslist AT 0x0408BF60> # MD1 have return, MD2 of view is not executed to jump directly to the Response MD2 process_response MD1 process_response
4)process_exception(self ,request, exception)
Parameters: request objects wsgi returned exception exception view function
Execution timing: in view of the implementation of the function, there is an abnormal situation
The order of execution: Press registration setting of reverse execution
return value:
The return value is null: the processing to the next process_exception
Returns the response object: Skip the other process_exception, start flashback sequence process_response execution (if any exception did not handle the exception, then the final will make an exception handled by django)
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import render, HttpResponse class MD1(MiddlewareMixin): def process_request(self, request): print('MD1 process_request') # return HttpResponse('拒绝访问') def process_response(self, request, response): print('MD1 process_response') # return HttpResponse('拒绝访问') return response def process_view(self, request, view_func, view_args, view_kwargs): print('MD1 process_view', view_func) def process_exception(self, request, exception): print('MD1 process_exception') print(exception) return HttpResponse(exception) class MD2(MiddlewareMixin): def process_request(self, request): print('MD2 process_request') # return HttpResponse('拒绝访问') defprocess_response (Self, Request, Response): Print ( ' MD2 process_response ' ) # return the HttpResponse ( 'access denied') return Response DEF process_view (Self, Request, view_func, view_args, view_kwargs): Print ( ' MD2 process_view ' ) DEF process_exception (Self, Request, Exception): Print ( ' MD2 process_exception ' ) Print (Exception)
### view function added an error, let process_exception capture,
MD1 process_request
MD2 process_request
MD1 process_view <function presslist at 0x03BAC078>
MD2 process_view
MD2 process_exception
invalid literal for int() with base 10: 'ok'
MD1 process_exception
invalid literal for int() with base 10: 'ok'
MD2 process_response
MD1 process_response
5)process_template_response(self,request,response)
Parameters: request the return of the object wsgi
Execution timing: The view function execution returns Templateresponse objects will be performed
Execution order: performing the reverse sequence setting register, if the type is set a plurality of intermediate results is the last
Return value: response Object (Templateresponse object)
Templateresponse objects: This object is similar to using a render, but also Httpresponse objects render eventual return of the current difference is that two objects can be modified templateresponse middleware!
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import render, HttpResponse class MD1(MiddlewareMixin): def process_request(self, request): print('MD1 process_request') # return HttpResponse('拒绝访问') def process_response(self, request, response): print('MD1 process_response') # return HttpResponse('拒绝访问') return response def process_view(self, request, view_func, view_args, view_kwargs): print('MD1 process_view', view_func) def process_exception(self, request, exception): print('MD1 process_exception') print(exception) return HttpResponse(exception) def process_template_response(self, request, response): response.context_data = {'author': 'ggg'} print('MD1 process_template_response') return response ##middle/middles.py 指定templateresponse返回的数据 class MD2(MiddlewareMixin): def process_request(self, request): print('MD2 process_request') # return HttpResponse('拒绝访问') def process_response(self, request, response): print('MD2 process_response') # return HttpResponse('拒绝访问') return response def process_view(self, request, view_func, view_args, view_kwargs): print('MD2 process_view') def process_exception(self, request, exception): print('MD2 process_exception') print(exception) def process_template_response(self, request, response): response.context_data = {'author': '7777'} print('MD2 process_template_response') return response ##视图函数返回编程templateresponse对象 from django.template.response import TemplateResponse def presslist(request): msg_all = models.presslist.objects.all() return TemplateResponse(request, 'cbs.html', {'msg': msg_all, 'author': 'qgw'})
5.session middleware optimization
The verification process of the session in place process_request
1. If the client does not have a cookie store sessionid jump to login function
2. If a user login access functions you do not need cookie
from django.utils.deprecation import MiddlewareMixin from django.shortcuts import render, HttpResponse, reverse, redirect, HttpResponseRedirect class MD1(MiddlewareMixin): """缺陷是如果login函数能跳过中间件就好了""" def process_request(self, request): if not request.session.get('auth') and request.path_info != reverse('tlogin'): nowurl = request.path_info url = reverse('tlogin') + '?next={}'.format(nowurl) if nowurl == reverse('tlogin'): url = reverse('tlogin') return redirect(url)
Csrf resolve security middleware