zoukankan      html  css  js  c++  java
  • Django 中间件理解

    中间件

    django 中的中间件(middleware),在django中,中间件其实就是一个类,在请求到来和结束后,django会根据自己的规则在合适的时机执行中间件中相应的方法。

    应用场景,对所有请求统一进行处理,例如做身份验证、黑名单检测等

    在django项目的settings模块中,有一个 MIDDLEWARE变量,其中每一个元素就是一个中间件,如下图。

    一个请求的往返都会经过中间件过滤。路径图如下;

     

    与mange.py在同一目录下的文件夹 Middle下的mi.py文件中的Row1

    中间件中可以定义四个方法,分别是:

    • process_request(self,request)   --->请求来的时候处理方式 
    • process_view(self, request, callback, callback_args, callback_kwargs)     --->获取请求url参数,修改views函数逻辑
    • process_template_response(self,request,response)
    • process_exception(self, request, exception)  --->异常处理专用,当自己写的views函数报错的时候,就执行,exception就是报错内容
    • process_response(self, request, response)  --->到请求处理函数后请求处理

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

    自定义中间件

    1、创建中间件类m1.py

     m1.py

    from django.utils.deprecation import MiddlewareMixin
    
    
    class Row1(MiddlewareMixin):
        def process_request(self, request):
            print('request Row1 ')
        def process_response(self,request,response):
            print('Row1-Response')
            return response
        
    
    class Row2(MiddlewareMixin):
        def process_request(self, request):
            print('request Row2 ')
        def process_response(self,request,response):
            print('Row2-Response')
            return response
    
    class Row3(MiddlewareMixin):
        def process_request(self, request):
            print('request Row3 ')
        def process_response(self,request,response):
            print('Row3-Response')
            return response

    2、注册中间件

    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',
        'Middle.m1.Row1',
        'Middle.m1.Row2',
        'Middle.m1.Row3',
    ]

    访问:

     测试中间process_response(self, request, response)返回HttpResonse对象,则直接将该对象返回给用户。

    class Row2(MiddlewareMixin):
        def process_request(self, request):
            print('request Row2 ')
        def process_response(self,request,response):
            print('Row2-Response')
            # return response
            return HttpResponse('OK')

    结果,任何请求到中间逻辑被返回

     process_view(self, request, callback, callback_args, callback_kwargs)

    process_view 函数执行流程在 process_request(self,request) 和 process_response(self,  request, response) 之间

    形参说明:

      callback:处理请求的最终自定义view函数

      callback_args:请求过来的url中具体的未命名正则分组变量 如

       callback_kwargs: 求过来的url中具体的已命名正则分组变量字典

          

     process_view 示例代码

    #!/usr/bin/env python3
    # -*- coding:utf-8 -*-
    #  @Time: 2020/7/21 22:58
    #  @Author:zhangmingda
    #  @File: m1.py
    #  @Software: PyCharm
    #  Description:
    
    from django.utils.deprecation import MiddlewareMixin
    from django.shortcuts import HttpResponse
    
    class Row1(MiddlewareMixin):
        def process_request(self, request):
            print('request Row1 ')
        def process_response(self,request,response):
            print('Row1-Response')
            return response
        def process_view(self,request, view_func, view_func_args, view_func_kwargs):
            print('Row1_process_view')
    
    
    class Row2(MiddlewareMixin):
        def process_request(self, request):
            print('request Row2 ')
        def process_response(self,request,response):
            print('Row2-Response')
            # return response
            return HttpResponse('OK')
        def process_view(self,request, view_func, view_func_args, view_func_kwargs):
            print('Row2_process_view')
    
    class Row3(MiddlewareMixin):
        def process_request(self, request):
            print('request Row3 ')
        def process_response(self,request,response):
            print('Row3-Response')
            return response
        def process_view(self,request, view_func, view_func_args, view_func_kwargs):
            print('Row2_process_view')

    测试url请求后端输出

    request Row1
    request Row2
    request Row3
    Row1_process_view
    Row2_process_view
    Row2_process_view
    [22/Jul/2020 12:56:53] "GET /session_login/ HTTP/1.1" 200 2
    Row3-Response
    Row2-Response
    Row1-Response

    process_exception(self, request, exception)  

    自定义中间件 m1.py中 某函数

        def process_exception(self,  request, exception):
            print(exception)
            if isinstance(exception,ValueError):
                return HttpResponse('出现异常:%s'% exception)

    views.py中故意报错测试int('a')

    class SessionIndex(View):
        def get(self,request):
            int('a')
            current_user = request.session.get('current_user')
            print(current_user)
            if current_user:
                return render(request, 'session_index.html')
            else:
                return redirect('/session_login/')

    请求访问,返回自定义错误提示

     process_template_response(self, request, response)

    当views.py 中 返回为一个对象,对象中有render()方法,此函数才被执行。下面举例ShaBi这个类实现对象。被返回

    views.py

    class ShaBi(object):
        def render(self):
            return HttpResponse('傻逼')
    
    
    class SessionIndex(View):
        def get(self,request):
            current_user = request.session.get('current_user')
            print(current_user)
            if current_user:
                return render(request, 'session_index.html')
            else:
                # return redirect('/session_login/')
                return ShaBi()

    m1.py

    class Row3(MiddlewareMixin):
        def process_template_response(self,request, response):
            print('傻逼无用逻辑')
            return response  # 将函数return的对象中render()函数返回值返回,浏览器访问就出现傻逼了

    后端输出

    request Row1
    request Row2
    request Row3
    Row1_process_view
    Row2_process_view
    Row2_process_view
    None
    傻逼无用逻辑
    Row3-Response
    Row2-Response
    Row1-Response
    [22/Jul/2020 13:59:35] "GET /session_index/ HTTP/1.1" 200 6

    浏览器获取到返回值

    <html><head></head><body>傻逼</body></html>



  • 相关阅读:
    每日leetcode-数组-387. 字符串中的第一个唯一字符
    每日leetcode-数组-541. 反转字符串 II
    每日leetcode-数组-344. 反转字符串
    每日leetcode-数组-58. 最后一个单词的长度
    每日leetcode-数组-434. 字符串中的单词数
    每日leetcode-数组-14. 最长公共前缀
    每日leetcode-数组-125. 验证回文串
    每日leetcode-数组-520. 检测大写字母
    Weblogic漏洞挖矿病毒解决方法
    C盘空间不足清理
  • 原文地址:https://www.cnblogs.com/zhangmingda/p/13359654.html
Copyright © 2011-2022 走看看