Django-MiddleWare

中间件中可以定义五个方法:

  1. process_request(self,request)

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

  3. process_template_response(self,request,response)

  4. process_exception(self, request, exception)

  5. process_response(self, request, response)


Django-MiddleWare_第1张图片


创建中间件

最基本的样子是:

class CommonMiddleware(object):
    def process_request(self, request):
        return None
 
    def process_response(self, request, response):
        return response

拓展后的样子是: 

class MiddleWare_Test(object):

    def process_request(self,request):
        pass
    def process_view(self, request, callback, callback_args, callback_kwargs):
        pass
    def process_exception(self, request, exception):
        pass
    def process_response(self, request, response):
        return response

 

比如说要创建一个拦截恶意访问的中间件:

class BlockedIpMiddleware(object):
    def process_request(self, request):
        if request.META['REMOTE_ADDR'] in getattr(settings, "BLOCKED_IPS", []):
            return http.HttpResponseForbidden('

Forbidden

')

注册中间件

MIDDLEWARE = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'xxx.xx.MiddleWare_Test'
    #xxx是目录,xx是py脚本名
)


 

你可能感兴趣的:(Django)