django中间件介绍
在学习django中间件之前,先来认识一下django的生命周期,如下图所示:

django生命周期:浏览器发送的请求会先经过wsgiref模块处理解析出request(请求数据)给到中间件,然后通过路由控制执行对应的视图函数,从而和模板,db进行交互,交互完的数据再通过视图函数返回给中间件,最后wsgiref模块将返回的数据封装成http形式的数据给到浏览器并进行展示。
了解了django的生命周期后,我们就可以开始着手写一个自己的中间件了,接下来认识几个常用的中间件方法
1.process_request
单个中间件
首先在app下创建一个py文件,定义你的中间件类名
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse class MiddlewareShow(MiddlewareMixin): def process_request(self, request): print('MiddlewareShow1')
然后将你的py文件路径写入django主项目的settings的MIDDLEWARE中
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',
'proxy_pro.middleware.MiddlewareShow' # 此条是新加的 从该项目路径开始写
]
然后执行一个视图函数即可,查看控制台打印

此时自己创建的process_request方法就生效了
多个中间件
此时在之前的py文件中再新建一个类
class MiddlewareShow(MiddlewareMixin):
def process_request(self, request):
print('MiddlewareShow1 Request')
class MiddlewareShowTwo(MiddlewareMixin):
def process_request(self, request):
print('MiddlewareShow2 Request')
然后将新建类的路径也放在django主项目的settings的MIDDLEWARE中
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',
'proxy_pro.middleware.MiddlewareShow',
'proxy_pro.middleware.MiddlewareShowTwo'
]
执行视图函数,查看控制台打印

此时定义的两个中间件都生效了,执行顺序是先1后2
2.process_response
分别在刚才的类中添加response方法
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse class MiddlewareShow(MiddlewareMixin): def process_request(self, request):
print('MiddlewareShow1 Request') def process_response(self, request, response):
print('MiddlewareShow1 Response')
return response class MiddlewareShowTwo(MiddlewareMixin): def process_request(self, request):
print('MiddlewareShow2 Request') def process_response(self, request, response):
print('MiddlewareShow2 Response')
return response
执行视图函数,查看控制台打印

此时可以看出请求先依次执行了中间件的Request,然后再去执行视图函数,返回是先执行跟后面的中间件再依次往前
这时突然冒出一个想法,如果在request时直接返回了某个东西,还会继续去执行后面的视图函数吗?那我们就来测试一下
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse class MiddlewareShow(MiddlewareMixin): def process_request(self, request):
print('MiddlewareShow1 Request')
return HttpResponse('request1时已返回') def process_response(self, request, response):
print('MiddlewareShow1 Response')
return response class MiddlewareShowTwo(MiddlewareMixin): def process_request(self, request):
print('MiddlewareShow2 Request') def process_response(self, request, response):
print('MiddlewareShow2 Response')
return response
执行视图函数,查看控制台

此时可以看出当request中有返回时,直接不执行后面的内容了
3.process_view
分别在刚才的py文件中添加view方法
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse class MiddlewareShow(MiddlewareMixin): def process_request(self, request):
print('MiddlewareShow1 Request') def process_response(self, request, response):
print('MiddlewareShow1 Response')
return response def process_view(self, request, callback, callback_args, callback_kwargs):
print('MiddlewareShow1 process_view') class MiddlewareShowTwo(MiddlewareMixin): def process_request(self, request):
print('MiddlewareShow2 Request') def process_response(self, request, response):
print('MiddlewareShow2 Response')
return response def process_view(self, request, callback, callback_args, callback_kwargs):
print('MiddlewareShow2 process_view')
执行视图函数,查看控制台返回

此时可以看出这个process_view方法会在执行完request后执行,执行完再去执行视图函数
这时候就有疑问了,那这个有什么用呢?我们先把它里面的参数打印一下
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse class MiddlewareShow(MiddlewareMixin): def process_request(self, request):
print('MiddlewareShow1 Request') def process_response(self, request, response):
print('MiddlewareShow1 Response')
return response def process_view(self, request, callback, callback_args, callback_kwargs):
print('MiddlewareShow1 process_view')
print('=====>callback', callback)
print('=====>callback_args', callback_args) class MiddlewareShowTwo(MiddlewareMixin): def process_request(self, request):
print('MiddlewareShow2 Request') def process_response(self, request, response):
print('MiddlewareShow2 Response')
return response def process_view(self, request, callback, callback_args, callback_kwargs):
print('MiddlewareShow2 process_view')
执行视图函数打印结果

此时可以看到这个view里面的参数callback是视图方法,callback_args是请求参数,那我们试着去请求下看看
class MiddlewareShow(MiddlewareMixin):
def process_request(self, request):
print('MiddlewareShow1 Request')
def process_response(self, request, response):
print('MiddlewareShow1 Response')
return response
def process_view(self, request, callback, callback_args, callback_kwargs):
print('MiddlewareShow1 process_view')
print('=====>callback', callback)
print('=====>callback_args', callback_args)
ret = callback(callback_args) # 请求
return ret
class MiddlewareShowTwo(MiddlewareMixin):
def process_request(self, request):
print('MiddlewareShow2 Request')
def process_response(self, request, response):
print('MiddlewareShow2 Response')
return response
def process_view(self, request, callback, callback_args, callback_kwargs):
print('MiddlewareShow2 process_view')
查看打印结果

结果显然易见,请求视图函数成功了,返回了以后就没有去执行process_view2了,这边的作用就是可以拦截请求
4.process_exception
分别在刚才的py文件中添加exception方法
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse class MiddlewareShow(MiddlewareMixin): def process_request(self, request):
print('MiddlewareShow1 Request') def process_response(self, request, response):
print('MiddlewareShow1 Response')
return response def process_view(self, request, callback, callback_args, callback_kwargs):
print('MiddlewareShow1 process_view')
# print('=====>callback', callback)
# print('=====>callback_args', callback_args)
# ret = callback(callback_args)
# return ret def process_exception(self, request, exception):
print('MiddlewareShow1 process_exception')
return HttpResponse(exception) class MiddlewareShowTwo(MiddlewareMixin): def process_request(self, request):
print('MiddlewareShow2 Request') def process_response(self, request, response):
print('MiddlewareShow2 Response')
return response def process_view(self, request, callback, callback_args, callback_kwargs):
print('MiddlewareShow2 process_view') def process_exception(self, request, exception):
print('MiddlewareShow2 process_exception')
return HttpResponse(exception)
执行视图函数,查看控制台

问题来了,为啥没有走这个中间件方法呢?别慌,我们在视图函数中加个错
def middle_show(request):
leo print('执行了视图函数') return HttpResponse('hhh')
此时在执行下看看

此时可以看到当process_exception2获取到报错后,就返回了没有执行process_exception1
那如果我们在process_exception1处理呢,我们来测试下
from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse class MiddlewareShow(MiddlewareMixin): def process_request(self, request):
print('MiddlewareShow1 Request') def process_response(self, request, response):
print('MiddlewareShow1 Response')
return response def process_view(self, request, callback, callback_args, callback_kwargs):
print('MiddlewareShow1 process_view')
# print('=====>callback', callback)
# print('=====>callback_args', callback_args)
# ret = callback(callback_args)
# return ret def process_exception(self, request, exception):
print('MiddlewareShow1 process_exception')
return HttpResponse(exception) class MiddlewareShowTwo(MiddlewareMixin): def process_request(self, request):
print('MiddlewareShow2 Request') def process_response(self, request, response):
print('MiddlewareShow2 Response')
return response def process_view(self, request, callback, callback_args, callback_kwargs):
print('MiddlewareShow2 process_view') def process_exception(self, request, exception):
print('MiddlewareShow2 process_exception')
执行视图函数,打印看下

此时还会走到process_exception1哦,然后把错误返回给页面。
以上就是django中间件的介绍,希望和大家多多学习!转载请说明出处,尊重劳动成果!!!
django中间件介绍的更多相关文章
- python Django 中间件介绍
我们一直都在使用中间件,只是没有注意到而已,打开Django项目的Settings.py文件,看到下面的MIDDLEWARE配置项,django默认自带的一些中间件: MIDDLEWARE = [ ' ...
- {Django基础九之中间件} 一 前戏 二 中间件介绍 三 自定义中间件 四 中间件的执行流程 五 中间件版登陆认证
Django基础九之中间件 本节目录 一 前戏 二 中间件介绍 三 自定义中间件 四 中间件的执行流程 五 中间件版登陆认证 六 xxx 七 xxx 八 xxx 一 前戏 我们在前面的课程中已经学会了 ...
- 【12】Django 中间件
前戏 我们在前面的课程中已经学会了给视图函数加装饰器来判断是用户是否登录,把没有登录的用户请求跳转到登录页面.我们通过给几个特定视图函数加装饰器实现了这个需求.但是以后添加的视图函数可能也需要加上装 ...
- Django中间件2
前戏 我们在前面的课程中已经学会了给视图函数加装饰器来判断是用户是否登录,把没有登录的用户请求跳转到登录页面.我们通过给几个特定视图函数加装饰器实现了这个需求.但是以后添加的视图函数可能也需要加上装饰 ...
- 自定义Django中间件(登录验证中间件实例)
前戏 我们在前面的课程中已经学会了给视图函数加装饰器来判断是用户是否登录,把没有登录的用户请求跳转到登录页面.我们通过给几个特定视图函数加装饰器实现了这个需求.但是以后添加的视图函数可能也需要加上装饰 ...
- Django 2.0 学习(20):Django 中间件详解
Django 中间件详解 Django中间件 在Django中,中间件(middleware)其实就是一个类,在请求到来和结束后,Django会根据自己的规则在合适的时机执行中间件中相应的方法. 1. ...
- Django中间件的5种自定义方法
阅读目录(Content) Django中间件 自定义中间件 中间件(类)中5种方法 中间件应用场景 回到顶部(go to top) Django中间件 在http请求 到达视图函数之前 和视图函 ...
- Django 中间件使用
前戏 我们在前面的课程中已经学会了给视图函数加装饰器来判断是用户是否登录,把没有登录的用户请求跳转到登录页面.我们通过给几个特定视图函数加装饰器实现了这个需求.但是以后添加的视图函数可能也需要加上装 ...
- Django中间件如何处理请求
Django中间件 在http请求 到达视图函数之前 和视图函数return之后,django会根据自己的规则在合适的时机执行中间件中相应的方法. Django1.9版本以后中间件的执行流程 1. ...
随机推荐
- Web信息收集之搜索引擎-Shodan Hacking
Web信息收集之搜索引擎-Shodan Hacking 一.Shodan Hacking简介 1.1 ip 1.2 Service/protocol 1.3 Keyword 1.4 Cuuntry 1 ...
- Linux常用命令详解(第三章)(ping、kill、seq、du、df、free、date、tar)
本章命令(共7个): 1 2 3 4 5 6 7 8 ping kill seq du df free date tar 1." ping " 作用:向网络主机发送ICMP(检测主 ...
- 20000套免费ppt模板获取攻略
前言 又到年末了,发现需要用到简历,PPT这些的地方又多了.PPT这东西吧,颜值真的很重要,毕竟老板拉融资都是用ppt拉来的.只要ppt够精美,外加上你的故事讲得好,A轮指定不是问题呀.往小处说,就是 ...
- MapReduce参数调优
原文链接:http://blog.javachen.com/2014/06/24/tuning-in-mapreduce/ 本文主要记录Hadoop 2.x版本中MapReduce参数调优,不涉及Ya ...
- Trap HDU - 6569 二分
题意: 给你n个边长ai,你需要挑出来4个边使得它们可以构成等腰梯形.问你能构成多少种不同的等腰梯形 题解: 我们首先处理一下边长为x的且这个边长出现大于等于2次的边,因为等腰梯形需要两条相等的边 然 ...
- Buy the Ticket HDU - 1133 大数dp
题意: 演唱会门票售票处,那里最开始没有零钱.每一张门票是50元,人们只会拿着100元和50元去买票,有n个人是拿着50元买票,m个人拿着100元去买票. n+m个人按照某个顺序按序买票,如果一个人拿 ...
- python爬取网易翻译 和MD5加密
一.程序需要知识 1.python中随机数的生成 # 生成 0 ~ 9 之间的随机数 # 导入 random(随机数) 模块 import random print(random.randint(0, ...
- poj3087 Shuffle'm Up
Description A common pastime for poker players at a poker table is to shuffle stacks of chips. Shuff ...
- hdu3033 I love sneakers!
Problem Description After months of hard working, Iserlohn finally wins awesome amount of scholarshi ...
- 洛谷P2241-统计方形-矩形内计算长方形和正方形的数量
洛谷P2241-统计方形 题目描述: 有一个 \(n \times m\) 方格的棋盘,求其方格包含多少正方形.长方形(不包含正方形). 思路: 所有方形的个数=正方形的个数+长方形的个数.对于任意一 ...