django中间件

时间:2024-10-10 16:11:12

1.跨站请求伪造

中间件的执行顺序从上往下的读

MIDDLEWARE = [   # 从上往下的读
    '',
    '',
    '',
    # '',
    '',
    '',
    '',
    '.MyMiddleware1',# 
    '.MyMiddleware2',
]

新建一个文件

与这个文件代码顺序无关

from  import MiddlewareMixin

class MyMiddleware2(MiddlewareMixin):
    def process_request(self,request):
        print('MyMiddleware--------2------->')

class MyMiddleware1(MiddlewareMixin):
    def process_request(self,request):
        print('MyMiddleware--------1------->')

2.process_request 执行顺序从上往下

请求来的时候,会响应它

http://127.0.0.1:8000/test_middle/?name=shouyue 
输入这个网站 用GET提取shouyue

3.process_response 执行顺序从下往上

响应回去的时候,会走它

错误示范

from  import MiddlewareMixin
class MyMiddleware2(MiddlewareMixin):
    def process_request(self,request):
        print('MyMiddleware--------request2------->')
    def process_response(self,request,response):
        print('MyMiddleware--------response2------->')
class MyMiddleware1(MiddlewareMixin):
    def process_request(self,request):
        print('MyMiddleware--------request1------->')
    def process_response(self, request, response):
        print('MyMiddleware--------response1------->')

报错

if ('X-Frame-Options') is not None:
AttributeError: 'NoneType' object has no attribute 'get'
[13/Jan/2021 15:03:22] "GET /test_middle/?name=shouyue HTTP/1.1" 500 58271

原因

# 文件第一次返回响应
def test_middle(