当前位置:   article > 正文

【Django】Django实现对IP地址访问过滤_django 限制 国内 ip 访问

django 限制 国内 ip 访问

【Django】Django实现对IP地址访问过滤

一、编写中间件

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地址被禁止')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

二、设置

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地址过滤
]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/71715
推荐阅读
相关标签
  

闽ICP备14008679号