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

标签 python fastapi

我有两个函数,并且使用类似的参数,但其中一个函数按预期工作,而另一个函数则不然:

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"]}

第一个功能完美运行。第二个返回此错误:

{
    "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)

关于python - fastapi 主体在两个函数之间表现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68370277/

相关文章:

python - IntelliJ conda 集成

jinja2 - 如何将模板位置传递给 FastAPI 中的所有 View

python - 从数据帧中删除 header 索引

python - MagicMock @patch 没有按我的预期工作

python - 处理 Ctype 中的默认参数

Python 3 正则表达式单词边界不清楚

python - FastAPI:如何仅为特定端点启用 CORS?

python - 唯一约束验证的最佳实践

python - 如何在 FastAPI 的 CORS 中间件中正确使用正则表达式?

python - 在 python-fastApi 中间件中引发异常