First: The path structure
如果没有,则需要按照以下 struct 在应用程序中创建middleware文件夹:
yourproject/yourapp/middleware
The folder middleware should be placed in the same folder as settings.py, urls, templates...
Important: Don't forget to create the init.py empty file inside the middleware folder so your app recognizes this folder
Second: Create the middleware
现在我们应该为我们的定制中间件创建一个文件,在本例中,假设我们想要一个基于IP过滤用户的中间件,我们在middleware文件夹中创建一个名为filter_ip_middleware.py的文件,代码如下:
class FilterIPMiddleware(object):
# Check if client IP is allowed
def process_request(self, request):
allowed_ips = ['192.168.1.1', '123.123.123.123', etc...] # Authorized ip's
ip = request.META.get('REMOTE_ADDR') # Get client IP
if ip not in allowed_ips:
raise Http403 # If user is not allowed raise Error
# If IP is allowed we don't do anything
return None
Third: Add the middleware in our 'settings.py'
我们需要寻找:
MIDDLEWARE_CLASSES
(django < 1.10)
MIDDLEWARE
(django >= 1.10)
在设置中.我们需要添加我们的中间件(Add it in the last position).它应该是这样的:
MIDDLEWARE = ( # Before Django 1.10 the setting name was 'MIDDLEWARE_CLASSES'
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Above are django standard middlewares
# Now we add here our custom middleware
'yourapp.middleware.filter_ip_middleware.FilterIPMiddleware'
)
Done!现在,来自每个客户端的每个请求都将调用您的自定义中间件并处理您的自定义代码!