"""
simple middlware to block IP addresses via settings
variable BLOCKED_IPS
"""
from django.conf import settings
from django import http
class BlockedIpMiddleware(object):
def process_request(self, request):
if request.META['REMOTE_ADDR'] in settings.BLOCKED_IPS:
return http.HttpResponseForbidden('<h1>Forbidden</h1>')
return None
from django.conf import settings
from django import http
class BlockedIpMiddleware:
def __init__(self, get_response):
# One-time configuration and initialization, when the webserver starts.
self.get_response = get_response
def __call__(self, request):
# Code to be executed for each request before the view (and later
# middleware) are called.
# if request.META['REMOTE_ADDR'] in settings.BLOCKED_IPS:
if request.META['HTTP_X_REAL_IP'] in settings.BLOCKED_IPS:
return http.HttpResponseForbidden('<h1>Forbidden</h1>')
return self.get_response(request)
4条答案
按热度按时间p1iqtdky1#
只需将这个中间件类包含在
settings.py
文件中的'MIDDLEWARE_CLASSES'
变量下。还包括变量
BLOCKED_IPS = ('123.123.123.123',)
变量,其中的值是您希望从站点阻止的IP地址的元组。bmp9r5qi2#
看起来这就是我要找的...django-iprestrict.readthedocs.io/en/latest/configuration.html该软件包将允许或拒绝默认设置IP白名单或黑名单每个应用程序-
px9o7tmv3#
这部分是基于Ramesh K的回答,并在Django 2.2.19中进行了更改。在我使用的服务器上:负载平衡器将接收到的IP地址放入“X-Real-IP”报头(并且还将“X-Forwarded-For”报头作为逗号分隔的IP地址列表传递)。
8aqjt8rx4#
有一个我一直在关注的库,Django IP Restrict,我建议你给予一下,并告诉我们你的经验。