【问题标题】:Rate limit REST API made with connexion and swagger使用 connexion 和 swagger 制作的速率限制 REST API
【发布时间】:2021-06-04 10:50:39
【问题描述】:

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

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

问题是,如何为特定资源/路由/调用添加速率限制?

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

谢谢。

【问题讨论】:

    标签: python rest flask rate-limiting connexion


    【解决方案1】:

    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"
    
    

    【讨论】:

    • 你能分享一些你是如何完成这个的代码吗?我无法让烧瓶限制器使用连接应用程序。
    • @mcaulifn 我已经更新了使用 REDIS 进行缓存的最低限度
    【解决方案2】:

    您可以将 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"
    
      ....
    

    【讨论】:

    • 但是我在哪里准确设置请求的限制?因为,如果我理解正确,您所写的只是说明响应标头的速率限制。
    • 也许我误解了你在搜索什么,但速率限制基本上是提供者/服务器保护其底层基础设施的工具。这意味着调用服务的不是消费者会设置速率限制,而是服务器/提供者将指导调用者在一个时间范围内的速率限制是多少(X-Rate-Limit-Limit),调用后是多少离开专用于调用者的限制 (X-Rate-Limit-Remaining) 并且此速率限制将重置 (X-Rate-Limit-Reset) 到消耗的最大值。希望这个澄清会有所帮助。
    • 此外,提供者可以向客户端公开一个端点以获取速率限制的当前状态,类似于例如。 GitHub 正在做。请参阅docs.github.com/en/rest/reference/rate-limit GET /rate_limit 端点。
    • 感谢您的解释。我已经知道了。我的意思是,我是提供者,对吗?我正在使用 python 的连接模块开发 API 和所有端点。问题是,如何设置特定端点的速率限制?由于api基本上是在.YAML文件中定义的。
    • 从基础架构的角度来看还有一件事:通常速率限制不是提供者后端服务(您希望生成)的责任,而是例如。一个 API 网关,负责端点的节流功能。有关这种情况,请参见例如 AWS 文档:docs.aws.amazon.com/apigateway/latest/developerguide/…
    猜你喜欢
    • 1970-01-01
    • 2019-12-08
    • 2021-01-07
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    • 1970-01-01
    相关资源
    最近更新 更多