我有两个函数,并且使用类似的参数,但其中一个函数按预期工作,而另一个函数则不然:
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 复制而来的,它不接受股票代码作为输入,但可以向其发送原始列表。
最佳答案
两个函数的区别在于用户填写的参数数量。在第一个函数中,您有 tickers
和 func
,而在第二个函数中,您只有 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/