• Django的中间件


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

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

    应用:对所有请求或一部分请求做批量处理

    与mange.py在同一目录下,

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

    • process_request(self,request)
    • process_view(self, request, callback, callback_args, callback_kwargs) 如有有returnresponse则跳到最后
    • process_template_response(self,request,response)  视图函数的返回值中,如果有render方法,才被调用
    • process_exception(self, request, exception) 异常则跳到最后
    • process_response(self, request, response) 

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

                     

    案例:

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

    """
    Django settings for 中间件 project.
    
    Generated by 'django-admin startproject' using Django 1.11.2.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/1.11/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/1.11/ref/settings/
    """
    
    import os
    
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = '_u3mq4drv23_yumdj3_7ip62#n!vjbp74se*-qr%$35m@+-id&'
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True
    
    ALLOWED_HOSTS = []
    
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'app01',
    ]
    
    from django.middleware.common import CommonMiddleware
    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',
        'md.M1',
        'md.M2',
    ]
    
    ROOT_URLCONF = '中间件.urls'
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')]
            ,
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    
    WSGI_APPLICATION = '中间件.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/1.11/ref/settings/#databases
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
    
    
    # Password validation
    # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
    
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]
    
    
    # Internationalization
    # https://docs.djangoproject.com/en/1.11/topics/i18n/
    
    LANGUAGE_CODE = 'en-us'
    
    TIME_ZONE = 'UTC'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True
    
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/1.11/howto/static-files/
    
    STATIC_URL = '/static/'
    STATICFILES_DIRS = (
        os.path.join(BASE_DIR,'static'),
    )
    settings.py
    from django.shortcuts import render,HttpResponse,redirect
    
    # class JSONResponse:
    #     def __init__(self,req,status,msg):
    #         self.req = req
    #         self.status = status
    #         self.msg = msg
    #     def render(self):
    #         import json
    #         ret = {
    #             'status':self.status,
    #             'msg':self.msg
    #         }
    #         return HttpResponse(json.dumps(ret))
    #
    # def test(request):
    #     # print('test')
    #     # return HttpResponse("...")
    #     # ret = {}
    #     return JSONResponse(request,True,"错误信息")
    
    
    def test(request):
        print('test')
        return HttpResponse("...")
    views.py
    from django.utils.deprecation import MiddlewareMixin
    from django.shortcuts import HttpResponse
    class M1(MiddlewareMixin):
        def process_request(self,request):
            print('m1.process_request')
    
        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.process_response')
            return response
    
        def process_exception(self, request, exception):
            print('m1.process_exception')
    
        def process_template_response(self,request,response):
            """
            视图函数的返回值中,如果有render方法,才被调用
            :param request:
            :param response:
            :return:
            """
            print('m1.process_template_response')
            return response
    
    class M2(MiddlewareMixin):
        def process_request(self,request):
            print('m2.process_request')
        def process_view(self, request, callback, callback_args, callback_kwargs):
            print('m2.process_view')
        def process_response(self,request,response):
            print('m2.process_response')
            return response
        def process_exception(self, request, exception):
            print('m2.process_exception')
            return HttpResponse('错误了...')
    md.py

    process_template_response(self,request,response) 

    from django.shortcuts import render,HttpResponse,redirect
    
    class JSONResponse:
        def __init__(self,req,status,msg):
            self.req = req
            self.status = status
            self.msg = msg
        def render(self):
            import json
            ret = {
                'status':self.status,
                'msg':self.msg
            }
            return HttpResponse(json.dumps(ret))
    views.py

    md.py和settings.py上面一样。

  • 相关阅读:
    npm 中设置环境NODE_ENV变量,判断失败打印process.env.NODE_ENV确实是"development",但是判断process.env.NODE_ENV === "development" 是false
    NuxtJS踩坑日记,一步一步爬出我自己挖的坑。
    Django模型层1
    Django模板层2
    Centos 6.5 版本的下载教程
    上传文件到github
    CSS完整
    前端之JavaScript
    CSS
    多表 查询习题
  • 原文地址:https://www.cnblogs.com/luchuangao/p/7111527.html
Copyright © 2020-2023  润新知