自定义django中间件

自定义中间件

第一步:在根目录创建路径Middle/m1.py(注意如果是python2的话Middle下要有__init__.py文件,不然会报找不到模块错误)
m1.py的内容:
 1 # -*- coding: utf-8 -*-
 2 from django.utils.deprecation import MiddlewareMixin
 3 from django.shortcuts import HttpResponse
 4 
 5 class Row1(MiddlewareMixin):
 6     def process_request(self,request):
 7         print ('第一步')
 8 
 9     def process_view(self, request, view_func, view_func_args, view_func_kwargs):
10         print('中间第一步')
11 
12     def process_response(self,request,response):
13         print ('倒数第一步')
14         return  response
15 
16 class Row2(MiddlewareMixin):
17     def process_request(self,request):
18         print ('第2步')
19 
20     def process_view(self, request, view_func, view_func_args, view_func_kwargs):
21         print('中间第2步')
22 
23     def process_response(self,request,response):
24         print ('倒数第2步')
25         return  response
26 
27 class Row3(MiddlewareMixin):
28     def process_request(self,request):
29         print ('第3步')
30 
31     def process_view(self, request, view_func, view_func_args, view_func_kwargs):
32         print('中间第3步')
33 
34     def process_response(self,request,response):
35         print ('倒数第3步')
36         return  response
37 
38     def process_exception(self, request, exception):
39         if isinstance(exception,ValueError):
40             return HttpResponse('出现异常》。。')
41 
42     def process_template_response(self,request,response):
43         # 如果Views中的函数返回的对象中,具有render方法
44         print('-----------------------')
45         return response
View Code
项目setting.py中间件的内容:
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',
    'Middle.m1.Row1',
    'Middle.m1.Row2',
    'Middle.m1.Row3',
]
View Code

实际输出结果:

第一步
第2步
倒数第2步
倒数第一步
View Code

中间件的作用流程

 

实际的请求流程图:

 

 

 

posted @ 2018-05-06 22:04  梦中琴歌  阅读(276)  评论(0编辑  收藏  举报