【问题标题】:How do I get aiohttp-swagger to recognize GET query variables?如何让 aiohttp-swagger 识别 GET 查询变量?
【发布时间】:2018-07-26 16:01:18
【问题描述】:

我想在我的 python 项目中使用 aiohttp-swagger,但我不知道它如何处理 GET URL 和 POST 有效负载变量。我有这个基于quick start example here 的示例代码。我所做的唯一更改是在 GET URL 中包含了一个查询参数。

from aiohttp import web
from aiohttp_swagger import *


async def ping(request):
    """
    ---
    description: This end-point allow to test that service is up.
    tags:
    - Health check
    produces:
    - text/plain
    responses:
        "200":
            description: successful operation. Return "pong" text
        "405":
            description: invalid HTTP Method
    """
    return web.Response(text="pong %s" % request.match_info['var']) # change here (1/2)


app = web.Application()
app.router.add_route('GET', "/ping/{var}", ping) # change here (2/2)

setup_swagger(app)

web.run_app(app, host="127.0.0.1")

生成的 Swagger/OpenAPI 页面似乎不知道该变量。我预计它会生成一个文本框,我可以在其中填写“var”查询变量的值。我如何使用 aio-http 做到这一点?可能吗?如果没有,是否有其他库可以处理这个问题?

为了记录,我有 C# 背景,我过去曾使用 Swashbuckle library 完成此操作。

【问题讨论】:

    标签: python-3.x swagger aiohttp openapi


    【解决方案1】:

    您必须将parameters attr 添加到您的注释中。

    工作示例:

    from aiohttp import web
    from aiohttp_swagger import *
    
    
    async def ping(request):
        """
        ---
        description: This end-point allow to test that service is up.
        tags:
        - Health check
        parameters: 
        - in: query
          name: var
        produces:
        - text/plain
        responses:
            "200":
                description: successful operation. Return "pong" text
            "405":
                description: invalid HTTP Method
        """
        return web.Response(text="pong %s" % request.match_info['var']) # change here (1/2)
    
    
    app = web.Application()
    app.router.add_route('GET', "/ping/{var}", ping) # change here (2/2)
    
    setup_swagger(app)
    
    web.run_app(app, host="127.0.0.1")
    

    【讨论】:

    • 通过将参数“in”值从“query”更改为“path”,我的 URL 可以正常工作。对于“查询”,URL 将是“localhost:8888/ping{var}?var=abc”。对于“路径”,它是“localhost:8888/ping/abc”。我希望库有一种方法可以自动计算出参数,这样我就不必手动输入它们。这就是我习惯使用 C#/Swagger/Swashbuckle 的方式。
    猜你喜欢
    • 1970-01-01
    • 2014-05-17
    • 2020-02-01
    • 2018-11-24
    • 2023-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多