Django拦截器

目录:

 

mymiddleware.py

from django.utils.deprecation import  MiddlewareMixin

class MyMiddleware(MiddlewareMixin):

    def process_request(self,request):
        print("请求到达路由前执行")


    def process_view(self,request,callback,callback_args,callback_kwargs):
        print("请求达到视图前执行")

    def  process_response(self,request,response):
        print("请求响应前执行")
        return response

 

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.MyMiddleware',     # 配置拦截器路径
]

 

请求url

 

拦截器 mymiddleware.py 里面可以写多个拦截

如里面写2个类

class MyMiddleware1(MiddlewareMixin):

class MyMiddleware2(MiddlewareMixin):

里面的函数名一样

那么请求进来时 会分别1同时去走对应的拦截器,当其中一个拦截器有return时那么请求就结束了

 

 

参考: https://www.bilibili.com/video/BV1vK4y1o7jH?p=39&vd_source=caabcbd2a759a67e2a3de8acbaaf08ea

 

 

后记:

print(dir(request))
可以看到里面有很多方法可以用
比如:
request.method
request.get_raw_uri
equest.body

 

posted @ 2022-09-17 18:16  凯宾斯基  阅读(787)  评论(0编辑  收藏  举报