速率限制REST API由连接和型锻制成



我正在使用Flask和connexion构建一个REST API。(Python(

我正在使用swagger.yml文件将api添加到connexion应用程序中,该文件包含所有端点、方法等的定义…

问题是,如何为特定资源/路线/呼叫添加费率限制?

我似乎在文件中找不到它。

谢谢。

Connexion是一个烧瓶应用程序,许多与烧瓶相关的技术都与Connexion相关。

我们成功地使用Flask Limter进行速率限制。

import os
import connexion
APP = connexion.FlaskApp(
__name__, specification_dir=os.environ.get("OPENAPI_LOCATION", ".")
)
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import service.global_app as global_app
# This is for rate limiting (flask-limiter)
# Ref: https://limits.readthedocs.io/en/stable/storage.html#storage-scheme
APP.app.config["RATELIMIT_STORAGE_URI"] = (
"redis://" f"{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB + 1}"
)
# Kill switch for rate limiter
APP.app.config["RATELIMIT_ENABLED"] = True
# Policy for what to do if REDIS is down
APP.app.config["RATELIMIT_IN_MEMORY_FALLBACK"] = True
APP.app.config["RATELIMIT_HEADERS_ENABLED"] = True
APP.app.config["RATELIMIT_SWALLOW_ERRORS"] = os.environ.get("ENV", "") != "DEV"

LIMITER = Limiter(
global_app.APP.app,
key_func=get_remote_address,
# 1
default_limits=[DAILY_LIMIT, HOURLY_LIMIT],
)
@LIMITER.limit("3/second", override_defaults=True, exempt_when=exempt_when)
def simple_search_dsl_async(
) -> str:
return "Hi"

您可以使用X-Rate-Limit-*HTTP标头以及HTTP 429状态代码。

这实际上看起来像在openapi中:

....
responses:
"200":
description: Success response
content:
application/json:
schema:
$ref: "#/components/schemas/YourResponseModel"
headers:
"X-Rate-Limit-Limit": {
"description": "The number of allowed requests in the current period",
"schema": {
"type": "integer"
}
} ,
"X-Rate-Limit-Remaining": {
"description": "The number of remaining requests in the current period",
"schema": {
"type": "integer"
}
},
"X-Rate-Limit-Reset": {
"description": "The number of seconds left in the current period",
"schema": {
"type": "integer"
}
}
"429": 
description: Too many requests
content:
application/json:
schema:
$ref: "#/components/schemas/ErrorMessageResponse"
....

相关内容

  • 没有找到相关文章

最新更新