• python-day76--django-中间件


    什么是中间件?中间件应用场景?和装饰器区别?


    中间件 对于所有批量的请求用中间件合适,而对于某些请求个数少用装饰器合适
    - 中间件是什么? - 是一个类 - 方法名必须是process_request/process_response,否则无效 - 返回值注意: # 无返回值:继续执行后续中间件和视图函数 # 有返回值:执行自己的process_response和上面的response - 做过什么: - 用户登录验证 - csrf - session - 权限管理***
    ----------------------------------------------
    asd.a.py
            
    from django.conf import settings
    from django.shortcuts import redirect
    class MiddlewareMixin(object):
        def __init__(self, get_response=None):
            self.get_response = get_response
            super(MiddlewareMixin, self).__init__()
    
        def __call__(self, request):
            response = None
            if hasattr(self, 'process_request'):
                response = self.process_request(request)
            if not response:
                response = self.get_response(request)
            if hasattr(self, 'process_response'):
                response = self.process_response(request, response)
            return response
    
    
    class M1(MiddlewareMixin):
    
        def process_request(self,request):
            # 无返回值:继续执行后续中间件和视图函数
            # 有返回值:执行自己的process_response和上面的response
            # request.xxxx= 888
            # request.path_info # /login/
            if request.path_info == "/login/":
            # if request.path == "/login/":
                print(request.path)
                return None
            user_info = request.session.get(settings.SESS)
            if not user_info:
                return redirect('/login/')
    
        def process_response(self,request,response):
            print('m1.process_response')
            return response
    
    
    class M2(MiddlewareMixin):
    
        def process_request(self,request):
            print('m2.process_request')
    
        def process_response(self,request,response):
            print('m2.process_response')
            return response
      
    --------------------------------------------------        
    settings.py
    
    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',
        'asd.a.M1',
        'asd.a.M2',
    
    ]
    注意:必须在最后面加自定义的中间件

  • 相关阅读:
    shutdown -s -t
    企业计算模式
    数组的合并
    Cytoscape基础教程笔记
    初识Uniprot API
    常用生物信息 ID 及转换方法
    Gene Ontology (GO) 注释
    KEGG注释
    Install packages failed: Installing packages: error occurred. ------简单的问题常常会被忽略
    Cytoscape,Gephi ,mitlab network的比较
  • 原文地址:https://www.cnblogs.com/liuwei0824/p/7804128.html
Copyright © 2020-2023  润新知