pip3 install django-ratelimit
from ratelimit.decorators import ratelimit
@ratelimit(key='ip', rate='5/m', block=True)
def myview(request):
# 同一IP每分钟访问超过5次,会被限制
return HttpResponse()
from django.utils.decorators import method_decorator
class MyView(View):
@method_decorator(ratelimit(key='ip', rate='1/m', method='GET', block=True))
def get(self, request):
pass
@method_decorator(ratelimit(key='ip', rate='1/m', method='GET', block=True), name='get')
class MyOtherView(View):
def get(self, request):
pass
2.url的方式
from ratelimit.decorators import ratelimit
urlpatterns = [
path('/', ratelimit(key='ip', method='GET', rate='1/m', block=True)(MyView.as_view())),
]
pip3 install flask-limiter
from flask import Flask
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
app = Flask(__name__)
limiter = Limiter(
app,
key_func=get_remote_address,
default_limits=["10 per day", "5 per hour"]
)
@app.route("/func1")
@limiter.limit("1 per day")
def func1():
pass
@app.route("/func2")
@limiter.limit("1/second", override_defaults=False)
def func2():
pass
@app.route("/func3")
def func3():
pass
@app.route("/func4")
@limiter.exempt
def func4():
pass
默认经过请求的remote_address进行限制。
默认限制为10次/天,5次/小时;适用于全部路线
func1路由的限制将绕过默认的速率限制,为1次/天
func2路由继承默认限制,并增长了1次/秒的限制
func4路由不受任何默认速率限制的约束