覆盖FastAPI中自动生成的参数

2024-06-01 05:06:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写FastAPI程序,它只是一组用于查询数据的@app.get端点。他们可以使用许多不同的查询参数,这些参数是从配置文件自动生成的,例如@app.get("/ADJUST_COLOR/")端点可能看起来像/ADJUST_COLOR/?RED_darker=10&BLUE_lighter=43&GREEN_inverse=true,其中所有这些参数都是从颜色列表和对这些颜色执行的操作列表生成的(这只是一个例子,不是我实际正在做的事情)。
我这样做的方式是接收请求对象,如下所示:

@app.get("/ADJUST_COLOR/")
def query_COLORS( request: Request ):
    return look_through_parameters(request.query_params) 

但问题是,自动生成的招摇过市UI没有显示任何有用的数据:

因为我是手动解析请求的,所以没有生成任何参数。但是因为我有一个完整的参数列表,所以我应该能够生成自己的文档并让UI显示它

我已经看过这两份文件:https://fastapi.tiangolo.com/tutorial/path-operation-configuration/
https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/

但我无法确定这是否可能


Tags: 数据httpsappui列表参数get颜色
1条回答
网友
1楼 · 发布于 2024-06-01 05:06:31

您可以通过openapi_extra在路由中定义自定义api模式(这是FastAPI的最新功能,0.68可以使用,但我不确定支持此功能的最早版本):

@app.get("/ADJUST_COLOR/", openapi_extra={
    "parameters": [
        {
            "in": "query",
            "name": "RED_darker",
            "schema": {
                "type": "integer"
            },
            "description": "The level of RED_darker"
        },
        {
            "in": "query",
            "name": "BLUE_lighter",
            "schema": {
                "type": "integer"
            },
            "description": "The level of BLUE_lighter"
        },
        {
            "in": "query",
            "name": "GREEN_inverse",
            "schema": {
                "type": "boolean"
            },
            "description": "is GREEN_inverse?"
        },
    ]
})
async def query_COLORS(request: Request):
    return look_through_parameters(request.query_params)

在api /docs中呈现如下内容: enter image description here

相关问题 更多 >