赞
踩
在setting.py
同目录下新建middleware.py
,内容如下
from django.http import HttpResponse from django.utils.deprecation import MiddlewareMixin class IpMiddleware(MiddlewareMixin): def process_view(self, request, view_func, *view_args, **view_kwargs): ALLOW_IPS = [] for i in range(0, 200): ALLOW_IPS.append('192.168.0.' + str(i)) ALLOW_IPS.append('192.168.1.' + str(i)) if 'HTTP_X_FORWARDED_FOR' in request.META: ip = request.META['HTTP_X_FORWARDED_FOR'] else: ip = request.META['REMOTE_ADDR'] if ip not in ALLOW_IPS: return HttpResponse('您的IP地址被禁止')
MIDDLEWARE = [
'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',
'mysite.middleware.IpMiddleware', # 引入中间件,实现IP地址过滤
]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。