一.前言
我们前面和大家说了一下模板,今天要给大家讲解一下中间件了,什么是中间件呢,中间件顾名思义就是在请求进来到视图函数之间所进行的操作,中间件很简单,今天就给大家来介绍介绍中间件的基本用法

(某机构的图)
二.中间件的注册

先创建一个目录,习惯叫作middlewares,然后里面创建一个py文件,再定义一个类

我们再在settings里面的MIDDLEWARE把刚才定义的类给注册了,这样我们中间件就注册好了
三.原始方法

在 response=self.get_response(request)前面是中间件来的时候,后面是中间件来之后的


我们去看django的其他中间件,发现都继承了MiddlewareMixin这个类,我们发现这里面的__call__方法有这么一个东西,大概意思就是如果有process_request方法来就执行这个,有process_response走就执行这个,所以我们也可以通过这个模拟中间件
四.MiddlewareMixin

python
from django.utils.deprecation import MiddlewareMixin
class Md(MiddlewareMixin):
def process_request(self,request):
print('来了')
def process_response(self,request,response):
print('走了')
return response
我们通常都是这么定义中间件的,当然我们可以定义很多个中间件,他们的流程就是上图那样
五.中间件其他方法
这里给大家介绍一下中间件种不常用的方法,大家知道就行
5.1 process_view
python
def process_view(self,request,view_func,view_args,view_kwargs):
print('view1')
这里给大家补充个知识点就是,在process_request里面是还没进行路由匹配的,当执行完路由匹配之后,就会走这里
5.2 process_exception
python
def proess_exception(self,request,exception):
print('异常了',exception)
return HttpResponse('异常了')
这里是当视图函数出现报错的时候走这里
5.3 process_template_response

通常得这么定义才能用
python
def process_template_response(self,request,response):
#在视图函数中,返回的是TemplateResponse对象,会默认执行render方法
return response
这个基本上不用,相当于直接写return render(request,'layout.html')
六.总结
今天主要还是简单知识点,做个了解就行了,后期主要是在做登录,配合cookie还有跨域用得上中间件,大家不记得的话来看就行了

七.补充
下一期将和大家简单讲解一下orm,起个开头,具体的等下下次再讲,期待大家的点赞关注加收藏