python中间件

Posted konglingxi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python中间件相关的知识,希望对你有一定的参考价值。

1.中间件的方法

process_request(self,request)
process_view(self, request, callback, callback_args, callback_kwargs)
process_template_response(self,request,response)
process_exception(self, request, exception)
process_response(self, request, response

 2.中间件运行机制

  a.玩法1

from  django.utils.deprecation import MiddlewareMixin

class M1(MiddlewareMixin):
    def process_request(self, request):
        print(‘M1.request‘) 

    def process_view(self, request,callback,callback_args,callback_kwargs ):
        print("M1.process_view")
     
    def process_response(self, request, response):
        print(‘M1.response‘)
        return response 

class M2(MiddlewareMixin):
    def process_request(self, request):
        print(‘M2.request‘) 

    def process_view(self, request,callback,callback_args,callback_kwargs ):
        print("M2.process_view")
  
    def process_response(self, request, response):
        print(‘M2.response‘)
        return response

 

#### 输出结果
M1.request
M2.request
M1.process_view
M2.process_view
#执行views视图
M2.response
M1.response

   b.玩法2

from  django.utils.deprecation import MiddlewareMixin

class M1(MiddlewareMixin):
    def process_request(self, request):
        print(‘M1.request‘)
    # callback视图函数名称 callback_args,callback_kwargs 视图函数执行所需的参数
    def process_view(self, request,callback,callback_args,callback_kwargs ):
        print("M1.process_view")
        response=callback(request,*callback_args,**callback_kwargs)
        return response
    def process_response(self, request, response):
        print(‘M1.response‘)
        return response


class M2(MiddlewareMixin):
    def process_request(self, request):
        print(‘M2.request‘)  

    def process_view(self, request,callback,callback_args,callback_kwargs ):
        print("M2.process_view")
    def process_response(self, request, response):
        print(‘M2.response‘)
        return response

 

####输出结果
M1.request
M2.request
M1.process_view
#执行views视图函数
M2.response
M1.response

 

以上是关于python中间件的主要内容,如果未能解决你的问题,请参考以下文章

常用python日期日志获取内容循环的代码片段

python 有用的Python代码片段

Python 向 Postman 请求代码片段

python [代码片段]一些有趣的代码#sort

使用 Python 代码片段编写 LaTeX 文档

python 机器学习有用的代码片段