Django后端开发——中间件

文章目录


参考资料

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

c 复制代码
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

c 复制代码
from django.utils.deprecation import MiddlewareMixin


class 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

c 复制代码
def test_mw(request):
    print('---test_mw view in ---')
    return HttpResponse('--test-mw---')

mysite3/urls.py

c 复制代码
path('test_mw',views.test_mw),

多个中间件的执行顺序:请求时先注册的先执行,响应时先注册的后执行

练习

(持续更新中)


相关推荐
微尘85 分钟前
C语言存储类型 auto,register,static,extern
服务器·c语言·开发语言·c++·后端
weixin_419349799 分钟前
Python pdf转换为html
python·pdf
计算机学姐12 分钟前
基于PHP的电脑线上销售系统
开发语言·vscode·后端·mysql·编辑器·php·phpstorm
吉小雨19 分钟前
PyTorch经典模型
人工智能·pytorch·python
可愛小吉30 分钟前
Python 课程10-单元测试
开发语言·python·单元测试·tdd·unittest
student.J37 分钟前
傅里叶变换
python·算法·傅里叶
super_journey1 小时前
RabbitMq中交换机(Exchange)、队列(Queue)和路由键(Routing Key)
分布式·中间件·rabbitmq
Freak嵌入式1 小时前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
java·开发语言·数据结构·python·接口·抽象基类
码拉松1 小时前
千万不要错过,优惠券设计与思考初探
后端·面试·架构
crownyouyou2 小时前
最简单的一文安装Pytorch+CUDA
人工智能·pytorch·python