文章目录
- 参考资料
- 中间件
- 注册中间件
- settings.py
- middleware/mymiddleware.py
- mysite3/views.py
- mysite3/urls.py
- 练习
参考资料
B站网课:点击蓝色字体跳转
或复制链接至浏览器:https://www.bilibili.com/video/BV1vK4y1o7jH?p=39&vd_source=597e21cf34ffcdce468ba00be2177e8a
中间件
请求——输入
响应——输出
注册中间件
mysite3-new-directory-middleware
middleware-new-pythonfile-__init__双下划线
middleware-new-pythonfile-mymiddleware
settings.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','middleware.mymiddleware.MyMW',
]
middleware/mymiddleware.py
from django.utils.deprecation import MiddlewareMixinclass MyMW(MiddlewareMixin):def process_request(self,request):print('MyMW process_request do ---')def process_view(self,request,callback,callback_args,callback_kwargs):print('MyMW process_views do ---')def process_response(self,request,response):print('MyMW process_response do ---')return response
mysite3/views.py
def test_mw(request):print('---test_mw view in ---')return HttpResponse('--test-mw---')
mysite3/urls.py
path('test_mw',views.test_mw),
多个中间件的执行顺序:请求时先注册的先执行,响应时先注册的后执行
练习
(持续更新中)