中间件是用于修改Django 请求或响应对象的钩子的。放置来自Django docs的中间件 的定义。
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.
如果要修改请求(即发送到视图的HttpRequest对象),则可以使用中间件。或者,您可能想要修改从视图返回的HttpResponse对象。这些都可以通过使用中间件来实现。
您可能要在视图执行之前执行操作。在这种情况下,您将使用中间件。
Django提供了一些默认的中间件。例如:AuthenticationMiddleware
很多时候,您会在视图内部使用request.user。Django希望在执行任何视图之前先设置用户属性request
。Django采用中间件方法来完成此任务。因此Django提供了AuthenticationMiddleware,可以修改请求对象。
然后Django修改请求对象,如下所示:
from django.contrib import auth
from django.contrib.auth import load_backend
from django.contrib.auth.backends import RemoteUserBackend
from django.core.exceptions import ImproperlyConfigured
from django.utils.deprecation import MiddlewareMixin
from django.utils.functional import SimpleLazyObject
def get_user(request):
if not hasattr(request, '_cached_user'):
request._cached_user = auth.get_user(request)
return request._cached_user
class AuthenticationMiddleware(MiddlewareMixin):
def process_request(self, request):
assert hasattr(request, 'session'), (
"The Django authentication middleware requires session middleware "
"to be installed. Edit your MIDDLEWARE setting to insert "
"'django.contrib.sessions.middleware.SessionMiddleware' before "
"'django.contrib.auth.middleware.AuthenticationMiddleware'."
)
request.user = SimpleLazyObject(lambda: get_user(request))
class RemoteUserMiddleware(MiddlewareMixin):
"""
Middleware for utilizing Web-server-provided authentication.
If request.user is not authenticated, then this middleware attempts to
authenticate the username passed in the ``REMOTE_USER`` request header.
If authentication is successful, the user is automatically logged in to
persist the user in the session.
The header used is configurable and defaults to ``REMOTE_USER``. Subclass
this class and change the ``header`` attribute if you need to use a
different header.
"""
# Name of request header to grab username from. This will be the key as
# used in the request.META dictionary, i.e. the normalization of headers to
# all uppercase and the addition of "HTTP_" prefix apply.
header = "REMOTE_USER"
force_logout_if_no_header = True
def process_request(self, request):
# AuthenticationMiddleware is required so that request.user exists.
if not hasattr(request, 'user'):
raise ImproperlyConfigured(
"The Django remote user auth middleware requires the"
" authentication middleware to be installed. Edit your"
" MIDDLEWARE setting to insert"
" 'django.contrib.auth.middleware.AuthenticationMiddleware'"
" before the RemoteUserMiddleware class.")
try:
username = request.META[self.header]
except KeyError:
# If specified header doesn't exist then remove any existing
# authenticated remote-user, or return (leaving request.user set to
# AnonymousUser by the AuthenticationMiddleware).
if self.force_logout_if_no_header and request.user.is_authenticated:
self._remove_invalid_user(request)
return
# If the user is already authenticated and that user is the user we are
# getting passed in the headers, then the correct user is already
# persisted in the session and we don't need to continue.
if request.user.is_authenticated:
if request.user.get_username() == self.clean_username(username, request):
return
else:
# An authenticated user is associated with the request, but
# it does not match the authorized user in the header.
self._remove_invalid_user(request)
# We are seeing this user for the first time in this session, attempt
# to authenticate the user.
user = auth.authenticate(request, remote_user=username)
if user:
# User is valid. Set request.user and persist user in the session
# by logging the user in.
request.user = user
auth.login(request, user)
def clean_username(self, username, request):
"""
Allow the backend to clean the username, if the backend defines a
clean_username method.
"""
backend_str = request.session[auth.BACKEND_SESSION_KEY]
backend = auth.load_backend(backend_str)
try:
username = backend.clean_username(username)
except AttributeError: # Backend has no clean_username method.
pass
return username
def _remove_invalid_user(self, request):
"""
Remove the current authenticated user in the request which is invalid
but only if the user is authenticated via the RemoteUserBackend.
"""
try:
stored_backend = load_backend(request.session.get(auth.BACKEND_SESSION_KEY, ''))
except ImportError:
# backend failed to load
auth.logout(request)
else:
if isinstance(stored_backend, RemoteUserBackend):
auth.logout(request)
class PersistentRemoteUserMiddleware(RemoteUserMiddleware):
"""
Middleware for Web-server provided authentication on logon pages.
Like RemoteUserMiddleware but keeps the user authenticated even if
the header (``REMOTE_USER``) is not found in the request. Useful
for setups when the external authentication via ``REMOTE_USER``
is only expected to happen on some "logon" URL and the rest of
the application wants to use Django's authentication mechanism.
"""
force_logout_if_no_header = False
同样,您可能有一个可以与不同时区的用户一起使用的应用程序。您想在向用户显示任何页面时使用用户的时区。您想在所有视图中访问用户的时区。在这种情况下,在会话中添加它是有益的。因此,您可以添加这样的中间件:
class TimezoneMiddleware(object):
def process_request(self, request):
# Assuming user has a OneToOneField to a model called Profile
# And Profile stores the timezone of the User.
request.session['timezone'] = request.user.profile.timezone
TimezoneMiddleware依赖于request.user
。并且request.user
填充在AuthenticationMiddleware中。因此,我们编写的TimezoneMiddleware必须在Django的在元组设置.MIDDLEWARE_CLASSES中提供AuthenticationMiddleware之后进行。
在接下来的示例中,我们将对中间件的顺序有更多的了解。
AuthenticationMiddleware仅实现process_request,不实现process_response。你可以在这里检查
GZipMiddleware仅实现process_response,而不实现process_request或process_view。你可以在这里看到
确保您有一个带有URL和视图的Django的项目,并且能够访问该视图。由于我们将尝试使用进行多种操作request.user
,因此请确保为您正确设置了身份验证,并request.user
在此视图中显示正确的内容。
在任何应用程序中创建一个文件middleware.py。
我有一个所谓的应用books
,所以我正在读书/ middleware.py中编写了此应用
class BookMiddleware(object):
def process_request(self, request):
print "Middleware executed"
在MIDDLEWARE_CLASSES中添加此中间件
MIDDLEWARE_CLASSES = (
'books.middleware.BookMiddleware',
'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',
)
向任何网址提出请求。这应该在runserver控制台上打印
Middleware executed
修改BookMiddleware.process_request更改看起来像
class BookMiddleware(object):
def process_request(self, request):
print "Middleware executed"
print request.user
再次请求一个URL。这将引发错误。
'WSGIRequest' object has no attribute 'user'
发生这种情况是因为user
尚未设置属性request
。
现在更改中间件的顺序,刹车BookMiddleware在AuthenticationMiddleware之后
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'books.middleware.BookMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
向任何网址提出请求。这应该在runserver
控制台上打印
Middleware executed
<username>
这表明process_request
已在中间件上按设置中列出的顺序执行了该命令.MIDDLEWARE_CLASSES
您可以进一步验证。在您的middleware.py中添加另一个中间件类AnotherMiddleware(对象):
def process_request(self, request):
print "Another middleware executed"
也可以将中间件添加到MIDDLEWARE_CLASSES中。
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'books.middleware.BookMiddleware',
'books.middleware.AnotherMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
现在输出为:
Middleware executed
<username>
Another middleware executed
修改BookMiddleware,可以看起来像
class BookMiddleware(object):
def process_request(self, request):
print "Middleware executed"
print request.user
return HttpResponse("some response")
现在尝试任何网址,您的输出将是:
Middleware executed
<username>
您会注意到两件事:
因此,如果中间件的process_request()返回HttpResponse对象,则绕过任何后续中间件的process_request。同时查看执行被绕过。
注释“ return HttpResponse(“一些响应”)”,因此两个中间件的process_request继续执行。
将方法process_response添加到两个中间件
class AnotherMiddleware(object):
def process_request(self, request):
print "Another middleware executed"
def process_response(self, request, response):
print "AnotherMiddleware process_response executed"
return response
class BookMiddleware(object):
def process_request(self, request):
print "Middleware executed"
print request.user
return HttpResponse("some response")
#self._start = time.time()
def process_response(self, request, response):
print "BookMiddleware process_response executed"
return response
尝试一些网址。输出将是
Middleware executed
<username>
Another middleware executed
AnotherMiddleware process_response executed
BookMiddleware process_response executed
AnotherMiddleware.process_response()在BookMiddleware.process_response()之前执行,而AnotherMiddleware.process_request()在BookMiddleware.process_request()之后执行。因此,process_response()与process_request的操作相反。对最后一个中间件然后对最后一个中间件执行process_response(),依此类推,直到第一个中间件。
Django按照在MIDDLEWARE_CLASSES中自上而下定义的顺序应用中间件的process_view()。这是process_request()遵循的顺序。
同样,如果任何process_view()返回HttpResponse对象,则随后的process_view()调用将被忽略和不执行。