博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Django的中间件
阅读量:4949 次
发布时间:2019-06-11

本文共 6336 字,大约阅读时间需要 21 分钟。

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, seehttps://docs.djangoproject.com/en/1.11/topics/settings/For the full list of settings and their values, seehttps://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 = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_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 CommonMiddlewareMIDDLEWARE = [    '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/#databasesDATABASES = {    '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-validatorsAUTH_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 = TrueUSE_L10N = TrueUSE_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 MiddlewareMixinfrom django.shortcuts import HttpResponseclass 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 responseclass 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,redirectclass 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上面一样。

 

转载于:https://www.cnblogs.com/luchuangao/p/7111527.html

你可能感兴趣的文章
876-链表的中间结点
查看>>
BZOJ 3781 莫队
查看>>
BZOJ 3674/BZOJ 3673 主席树
查看>>
JAVA的String类
查看>>
wtforms 简单使用
查看>>
flume介绍
查看>>
eclipse优化总结
查看>>
java异常处理
查看>>
【操作系统】主存空间的分配和回收
查看>>
JZOJ 4.1 B组 俄罗斯方块
查看>>
AngularJS XMLHttpRequest
查看>>
bootstrap在reset.css文件中设置margin为0,因此其他的标签需要重新设计margin。
查看>>
OO前三次作业总结
查看>>
开发者账号申请附录
查看>>
R语言-shiny、knitr、printr、servr及tufte包
查看>>
平面三角形外心坐标推导
查看>>
poj 2586 Y2K Accounting Bug
查看>>
hiho#14
查看>>
单元测试5.2 心得
查看>>
spark总结
查看>>