• django-middleware中间件


    在django中,中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法。在django项目的settings模块中,有一个 MIDDLEWARE.
    中间件中可以定义如下方法。

    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)
    以上方法的返回值可以是None和HttpResonse对象,如果是None,则继续按照django定义的规则向下执行,如果是HttpResonse对象,则直接将该对象返回给用户。

    // 撰写中间件
    from django.utils.deprecation import MiddlewareMixin
    from django.shortcuts import HttpResponse
    class Middle1(MiddlewareMixin):
        def process_request(self, request):
            print("m1.process_request")
    
        def process_response(self, request, response):
            print("m1.process_response")
            return response
    
    
    class Middle2(MiddlewareMixin):
        def process_request(self, request):
            print("m2.process_request")
    
        def process_response(self, request, response):
            print("m2.process_response")
            return response
    
    
    //在settings中注册
    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',
        "my_middle.Middle1",
        "my_middle.Middle2",
    ]
    
    // 执行结果
    //m1.process_request
    //m2.process_request
    //执行视图函数
    //m2.process_response
    //m1.process_response
    
  • 相关阅读:
    I.MX6 简单电路模拟USB设备的插入
    I.MX6 查看baudrate确定是否被其他程序占用
    I.MX6 Ethernet MAC (ENET) MAC Address hacking
    I.MX6 MAC Address 导致的系统崩溃
    I.MX6 U-boot编译找不到用户目录
    I.MX6 i2c_data_write_byte ioctl error: I/O error
    I.MX6 Android shutdown shell command
    Where Are You Standing?
    byte[]和InputStream的相互转换
    jsp 获取cookie 的值的方法
  • 原文地址:https://www.cnblogs.com/zouruncheng/p/7103262.html
Copyright © 2020-2023  润新知