我正在尝试构建一个 RESTful API 应用程序flask_restful
,flask_jwt_extended
用于用户授权并将用户flask_limiter
的配额限制为 6/分钟。我的玩具/测试代码如下(尚未实施实际授权方案):
from flask import Flask, make_response
from flask_restful import Api, Resource
from flask_limiter import Limiter
from werkzeug.exceptions import HTTPException
from flask_jwt_extended import jwt_required, create_access_token, JWTManager, get_jwt_identity
# custom HTTP exception
class OutOfQuota(HTTPException):
code = 402
name = 'Out Of Quota'
app = Flask(__name__)
limiter = Limiter(app, key_func=get_jwt_identity)
api = Api(prefix='')
class Token(Resource):
def get(self, user):
return make_response({'token': create_access_token(identity=user)})
class Test(Resource):
@jwt_required
@limiter.limit('6/minute')
def get(self):
return make_response({'message': f'OK {get_jwt_identity()}'})
api.add_resource(Token, '/token/<string:user>')
api.add_resource(Test, '/test')
api.init_app(app)
# custom error handler (change "Payment Required" to "Out Of Quota" HTTP status
@app.errorhandler(429)
def ratelimit_handler(e):
return OutOfQuota(f'quota limit exceeded: {e.description}')
jwt = JWTManager(app)
app.config['JWT_SECRET_KEY'] = 'nothing-fancy-for-now'
if __name__ == '__main__':
app.run(host='localhost', port=8080)
端点/token
为用户生成一个 JWT 令牌,他们的用户名作为 JWT 身份存储在里面。当/test
使用此令牌访问端点时,我想检查此特定用户(即此特定身份)访问此端点的次数,因此使用get_jwt_identity
askey_func
的Limiter
.
/test
问题是我在运行上述代码时访问端点时没有任何限制;我可以随心所欲地访问它,尽可能快地访问它。我在这里错过了什么吗?