Django Middleware

Middleware是什么?

Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input or output.

工作流程

从浏览器发出一个请求 Request,得到一个响应后的内容 HttpResponse ,这个请求传递到 Django的过程如下:

process_request 被 process_view 替换

每一个请求都是先通过中间件中的 process_view 函数,这个函数返回 None 或者 HttpResponse 对象,如果返回前者,继续处理其它中间件,如果返回一个 HttpResponse,就处理中止,返回结果给浏览器。

process_view: https://docs.djangoproject.com/en/1.11/topics/http/middleware/#process_view

自定义Middleware

开发模式(DEBUG=True)禁用Middleware

在Middleware class的 init() 方法中 raise MiddlewareNotUsed

Django will then remove that middleware from the middleware process and log a debug message to the django.request logger when DEBUG is True.


定义方法

Response类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def simple_middleware(get_response):
# One-time configuration and initialization.

def middleware(request):
# Code to be executed for each request before
# the view (and later middleware) are called.

response = get_response(request)

# Code to be executed for each request/response after
# the view is called.

return response

return middleware

定义类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class SimpleMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.

def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.

response = self.get_response(request)

# Code to be executed for each request/response after
# the view is called.

return response

Django 1.10 定义类

class django.utils.deprecation.MiddlewareMixin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

call 方法会先调用 self.process_request(request),接着执行 self.get_response(request) 然后调用 self.process_response(request, response)

创建一个Middleware基类,后续Middleware直接继承重写即可

1
2
3
4
5
6
7
8
9
class BaseMiddleware(MiddlewareMixin):
def process_request(self, request):
return None

def get_response(self, request):
return None

def process_response(self, request, response):
return response