django中的中间件

一:django中的中间件可以在请求到达视图之前获取到请求所有数据,所以利用此特性可以作白/黑名单过滤及用户身份验证等操作:
二:      在django中定义一个中间件,需要继承自MiddlewareMixin三:在settings.py的配置文件的MIDDLEWARE部分中写添加以下配置:                        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',
    'app应用名.模块名.类名',

]

from django.utils.deprecation import MiddlewareMixin

class my_Middleware_1(MiddlewareMixin):
    def process_request(self, request):
        print("中间件1请求")

    def process_response(self, request, response):
        print("中间件1返回")
        response.data='abc'
        return response

    # def process_view(self, request, callback, callback_args, callback_kwargs):
    #     print("中间件1view")

    def process_exception(self, request, exception):
        pass
class my_Middleware_2(MiddlewareMixin):
    def process_request(self, request):
        print("中间件2请求")

    def process_response(self, request, response):
        print("中间件2返回")
        return response

    # def process_view(self, request, callback, callback_args, callback_kwargs):
    #     print("中间件2view")

    def process_exception(self, request, exception):
        pass
class my_Middleware_3(MiddlewareMixin):
    def process_request(self, request):
        print("中间件3请求")

    def process_response(self, request, response):
        print("中间件3返回")
        return response

    # def process_view(self, request, callback, callback_args, callback_kwargs):
    #     print("中间件3view")
    def process_exception(self, request, exception):
        pass

 

关注点:

         函数的执行顺序

posted @ 2018-04-12 23:20  雪纷飞  阅读(141)  评论(0编辑  收藏  举报