在学习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中间件介绍的更多相关文章

  1. python Django 中间件介绍

    我们一直都在使用中间件,只是没有注意到而已,打开Django项目的Settings.py文件,看到下面的MIDDLEWARE配置项,django默认自带的一些中间件: MIDDLEWARE = [ ' ...

  2. {Django基础九之中间件} 一 前戏 二 中间件介绍 三 自定义中间件 四 中间件的执行流程 五 中间件版登陆认证

    Django基础九之中间件 本节目录 一 前戏 二 中间件介绍 三 自定义中间件 四 中间件的执行流程 五 中间件版登陆认证 六 xxx 七 xxx 八 xxx 一 前戏 我们在前面的课程中已经学会了 ...

  3. 【12】Django 中间件

     前戏 我们在前面的课程中已经学会了给视图函数加装饰器来判断是用户是否登录,把没有登录的用户请求跳转到登录页面.我们通过给几个特定视图函数加装饰器实现了这个需求.但是以后添加的视图函数可能也需要加上装 ...

  4. Django中间件2

    前戏 我们在前面的课程中已经学会了给视图函数加装饰器来判断是用户是否登录,把没有登录的用户请求跳转到登录页面.我们通过给几个特定视图函数加装饰器实现了这个需求.但是以后添加的视图函数可能也需要加上装饰 ...

  5. 自定义Django中间件(登录验证中间件实例)

    前戏 我们在前面的课程中已经学会了给视图函数加装饰器来判断是用户是否登录,把没有登录的用户请求跳转到登录页面.我们通过给几个特定视图函数加装饰器实现了这个需求.但是以后添加的视图函数可能也需要加上装饰 ...

  6. Django 2.0 学习(20):Django 中间件详解

    Django 中间件详解 Django中间件 在Django中,中间件(middleware)其实就是一个类,在请求到来和结束后,Django会根据自己的规则在合适的时机执行中间件中相应的方法. 1. ...

  7. Django中间件的5种自定义方法

    阅读目录(Content) Django中间件 自定义中间件 中间件(类)中5种方法 中间件应用场景 回到顶部(go to top) Django中间件 在http请求 到达视图函数之前   和视图函 ...

  8. Django 中间件使用

     前戏 我们在前面的课程中已经学会了给视图函数加装饰器来判断是用户是否登录,把没有登录的用户请求跳转到登录页面.我们通过给几个特定视图函数加装饰器实现了这个需求.但是以后添加的视图函数可能也需要加上装 ...

  9. Django中间件如何处理请求

    Django中间件 在http请求 到达视图函数之前   和视图函数return之后,django会根据自己的规则在合适的时机执行中间件中相应的方法. Django1.9版本以后中间件的执行流程 1. ...

随机推荐

  1. Zabbix系列优秀博文

    Zabbix系列优秀博文 CSDN:菲宇:Zabbix专栏

  2. SparkStreaming与Kafka,SparkStreaming接收Kafka数据的两种方式

    SparkStreaming接收Kafka数据的两种方式 SparkStreaming接收数据原理 一.SparkStreaming + Kafka Receiver模式 二.SparkStreami ...

  3. UML——RUP(Rational Unified Process)

    一.宏观导图 二.论细节 RUP(Rational Unified Process)统一软件过程,是指要达到一个指定的目标而采取的一些系列有序的步骤,其目的是高效.准时地提交一个满足业务需求的软件产品 ...

  4. WPF 之 INotifyPropertyChanged 接口的使用 (一)

    一.INotifyPropertyChanged 的基本概念 ​ INotifyPropertyChanged 的作用:通知客户端属性值已经更改.详细信息见:INotifyPropertyChange ...

  5. 漫画 | CPU战争40年,真正的王者终于现身!

    上个世纪70年代,内存又慢又贵, 程序员得想尽一切办法节省内存. 那个时代的编译器也比较差劲 所以,70年代的程序员几乎都写得一手好汇编. 为了帮助程序员写好汇编,这个时候的CPU也有意把指令集做了增 ...

  6. 从云数据迁移服务看MySQL大表抽取模式

    摘要:MySQL JDBC抽取到底应该采用什么样的方式,且听小编给你娓娓道来. 小编最近在云上的一个迁移项目中被MySQL抽取模式折磨的很惨.一开始爆内存被客户怼,再后来迁移效率低下再被怼.MySQL ...

  7. [ZJOI2007]仓库建设(斜率dp优化)

    前言 纪念一下我做的第二道斜率优化$dp$题,终于自己能把代码敲出来了,然而有很智障的$bug$,把$i$写成$q[i]$,找了半天QAQ.然后写$dp$公式并优化的能力稍微强了一点(自我感觉良好), ...

  8. 2019牛客暑期多校训练营(第二场)E.MAZE(线段树+dp)

    题意:给你一个n*m的矩阵 你只能向左向右相下走 有两种操作 q次询问 一种是把一个单位翻转(即可走变为不可走 不可走变为可走) 另一种是询问从(1,x) 走到 (n,y)有多少种方案 思路:题目n为 ...

  9. Codeforces Round #604 (Div. 2) A. Beautiful String(贪心)

    题目链接:https://codeforces.com/contest/1265/problem/A 题意 给出一个由 a, b, c, ? 组成的字符串,将 ? 替换为 a, b, c 中的一个字母 ...

  10. python+fiddler 抓取抖音数据包并下载抖音视频

    这个我们要下载视频,那么肯定首先去找抖音视频的url地址,那么这个地址肯定在json格式的数据包中,所以我们就去专门查看json格式数据包 这个怎么找我就不用了,直接看结果吧 你找json包,可以选大 ...