django limit the number of requests per minute

bra*_*rad 1 python django request

i'm trying to limit the number of requests from an IP in case i get too many requests from it.

例如:如果我每分钟收到超过 50 个请求,我想阻止该 IP 5 分钟。

当我使用时,request.META['REMOTE_ADDR']我总是获得本地主机的 IP,而不是发送请求的 IP。

  1. 如何获取发送请求的计算机的 IP?
  2. 我如何限制该 IP 在 X 时间内不发送更多请求?

小智 6

django-ratelimit将限制您在给定时间内收到的请求数量。

安装:

pip install django-ratelimit
Run Code Online (Sandbox Code Playgroud)

在您看来:

from ratelimit.decorators import ratelimit

@ratelimit(key='ip', rate='10/m')
def myview(request):
...
Run Code Online (Sandbox Code Playgroud)


itz*_*nTV 1

1.如何获取发送请求的计算机的IP?

def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip

>>>get_client_ip(request)
"client ip"
Run Code Online (Sandbox Code Playgroud)

2.如何限制该IP在X时间内不发送更多请求?

我认为你可以为这种类型设置一个middleware类似在数据库中保存请求时间、将相邻请求与之前的请求进行比较之类的东西。

根据评论更新

如果您使用 nginx 作为 Web 服务器,请尝试此 http://nginx.org/en/docs/http/ngx_http_limit_req_module.html