flask-limiter限制单个IP访问的频率和次数

  Flask-Limiter provides rate limiting features to flask routes. It has support for a configurable backend for storage with current implementations for in-memory, redis and memcache. Flask-Limiter对flask的路由功能提供访问速率限制的功能。访问的信息可以存储到应用本身的内存里,或者存储到redis、memcache里

  

举例demo:

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,   //根据访问者的IP记录访问次数
    default_limits=["200 per day", "50 per hour"]  //默认限制,一天最多访问200次,一小时最多访问50次
)
@app.route("/slow")
@limiter.limit("1 per day")  //自定义访问速率
def slow():
    return "24"

@app.route("/fast")        //默认访问速率
def fast():
    return "42"

@app.route("/ping")
@limiter.exempt      //无访问速率限制
def ping():
    return "PONG"

效果:

$ curl localhost:5000/fast
42
$ curl localhost:5000/fast
42
$ curl localhost:5000/fast
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>429 Too Many Requests</title>
<h1>Too Many Requests</h1>
<p>2 per 1 minute</p>
$ curl localhost:5000/slow
24
$ curl localhost:5000/slow
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>429 Too Many Requests</title>
<h1>Too Many Requests</h1>
<p>1 per 1 day</p>
$ curl localhost:5000/ping
PONG
$ curl localhost:5000/ping
PONG
$ curl localhost:5000/ping
PONG
$ curl localhost:5000/ping
PONG

注释:

The built in flask static files routes are also exempt from rate limits.

即静态文件的访问无速率限制

 

文档说明:http://flask-limiter.readthedocs.io/en/stable/

github地址:https://github.com/alisaifee/flask-limiter

 

 

参考:

1、https://www.helplib.com/GitHub/article_107460

2、https://www.jianshu.com/p/dd29529b06d9

3、

4、

posted @ 2018-05-10 14:03  脚本小娃子  阅读(8824)  评论(0编辑  收藏  举报