fastapi 主体在两个函数之间表现不同

fastapi body behaving differently between two functions

我有两个函数,我使用的参数相似,但其中一个函数按预期工作,而另一个函数却没有:

from fastapi import FastAPI, Header, HTTPException, Body

@app.post("/portfolio/analytics/carbon-footprint", dependencies=[Depends(api_counter)])
async def getPortfolioCarbonFootprint(
    tickers: list = Body(...),
    func: str = Body(...),
    http_client: aiohttp.ClientSession = fastapi.Depends(http_client)
):
  
    print(tickers)
    return res

#historical prices
@app.post("/portfolio/analytics/historicalprices", dependencies=[Depends(api_counter)])
async def getPortfolioHistoricalPrices(
    tickers: list = Body(...),
    http_client: aiohttp.ClientSession = fastapi.Depends(http_client)
):
  
    print(tickers)
    jsonResults = await getHistoricalPrices(tickers)
    return jsonResults

对于两者,我都发送这个 json:

{"tickers" : [ "IBM.US", "MSFT.US"]}

第一个功能完美运行。第二个returns这个错误:

{
    "detail": [
        {
            "loc": [
                "body"
            ],
            "msg": "value is not a valid list",
            "type": "type_error.list"
        }
    ]
}

这就是它变得奇怪的地方。如果我发送这个:

[ "IBM.US", "MSFT.US"]

然后它按预期工作。

所以函数 1 工作正常。函数 2 是从函数 1 复制而来的,它不接受代码作为输入,但可以向它发送原始列表。

两个函数的区别在于需要用户填写的参数个数。在第一个函数中你有 tickersfunc,而在第二个函数中你只有 tickers.

来自 FastAPI 文档:

But if you have only a single item body parameter from a Pydantic model Item.

By default, FastAPI will then expect its body directly.

But if you want it to expect a JSON with a key item and inside of it the model contents, you can use the special Body parameter embed

所以在第二个函数中,如果要有key,就必须这样写:

tickers: list = Body(..., embed=True)