我如何限制每个用户的 Flask 应用程序速率?
How can I rate-limit my Flask application per user?
https://flask-limiter.readthedocs.io/en/stable/
我正在查看 Flask-Limiter 的文档,但我无法找到如何对每个用户进行速率限制,一切都是全局的。例如,不是将它设置为所有用户最多 200 个请求,而是如何让它每天由单个用户发出 200 个请求? (IP,或者其他我不知道用什么的标识)
我在 recipes 中找到了这个:
Rate limiting a route by current user (using Flask-Login):
@route("/test")
@login_required
@limiter.limit("1 per day", key_func = lambda : current_user.username)
def test_route():
return "42"
已更新:添加了简单示例
这是一个简单的 Flask 应用程序,它实现了配方,可以让您更好地理解:
from flask import Flask, redirect
from flask_login import (
LoginManager,
UserMixin,
current_user,
login_required,
login_user,
logout_user
)
from flask_limiter import Limiter
app = Flask(__name__)
# flask-login
app.secret_key = 'super secret string'
login_manager = LoginManager()
login_manager.init_app(app)
# flask-limiter
limiter = Limiter(app)
# user class
class User(UserMixin):
def __init__(self, id):
self.id = id
self.username = id
# memory storage
users = [User('user')]
@login_manager.user_loader
def load_user(user_id):
return users[0]
@app.route('/')
def index():
return 'Hello, World!'
@app.route('/login')
def login():
if not current_user.is_authenticated:
login_user(users[0])
return redirect('/secured')
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect('/')
@app.route('/secured')
@login_required
@limiter.limit("2 per day", key_func = lambda : current_user.username)
def secured():
return f"Hello, {current_user.id}"
if __name__ == '__main__':
app.run()
https://flask-limiter.readthedocs.io/en/stable/
我正在查看 Flask-Limiter 的文档,但我无法找到如何对每个用户进行速率限制,一切都是全局的。例如,不是将它设置为所有用户最多 200 个请求,而是如何让它每天由单个用户发出 200 个请求? (IP,或者其他我不知道用什么的标识)
我在 recipes 中找到了这个:
Rate limiting a route by current user (using Flask-Login):
@route("/test")
@login_required
@limiter.limit("1 per day", key_func = lambda : current_user.username)
def test_route():
return "42"
已更新:添加了简单示例
这是一个简单的 Flask 应用程序,它实现了配方,可以让您更好地理解:
from flask import Flask, redirect
from flask_login import (
LoginManager,
UserMixin,
current_user,
login_required,
login_user,
logout_user
)
from flask_limiter import Limiter
app = Flask(__name__)
# flask-login
app.secret_key = 'super secret string'
login_manager = LoginManager()
login_manager.init_app(app)
# flask-limiter
limiter = Limiter(app)
# user class
class User(UserMixin):
def __init__(self, id):
self.id = id
self.username = id
# memory storage
users = [User('user')]
@login_manager.user_loader
def load_user(user_id):
return users[0]
@app.route('/')
def index():
return 'Hello, World!'
@app.route('/login')
def login():
if not current_user.is_authenticated:
login_user(users[0])
return redirect('/secured')
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect('/')
@app.route('/secured')
@login_required
@limiter.limit("2 per day", key_func = lambda : current_user.username)
def secured():
return f"Hello, {current_user.id}"
if __name__ == '__main__':
app.run()