我正试着用FastAPI归还一本字典。我搜索了他们的网站,却找不到任何有用的东西。也许我说的是完全错误的,但我可以想象我可以给它一个结果字典,它会返回它们作为结构在字典中?最终的目标是将这些信息从数据库中提取出来,但是为了简单和测试,我已经把它缩小到了这个范围。
from typing import List, Optional
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: float = 10.5
tags: List[str] = []
class Items(BaseModel):
items: List[Item]
itemslist = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
"baz": {"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
}
@app.get("/items", response_model=Items, response_model_exclude_unset=True)
async def read_item(Items: dict):
return Items(items=itemslist)当我打开页面时
{
"detail": [
{
"loc": [
"body"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}在控制台日志中我看到
127.0.0.1:53845 - "GET /items HTTP/1.1" 422 Unprocessable Entity发布于 2021-08-31 17:31:28
您的代码有几个问题:
get端点的函数定义中指定一个参数时,该参数将被期望在正文中发送。这就是为什么错误消息在body字段中显示loc .的原因。
@app.get("/items", response_model=Items, response_model_exclude_unset=True)
async def read_item():
return Items(items=itemslist)itemslist定义为dict,但希望将其转换为list。另外,通常情况下,数据库适配器将返回行或类似的list。这就是为什么我会把它改为这样的东西:itemslist = [
{"name": "Foo", "price": 50.2},
{"name": "Bar", "description": "The bartenders", "price": 62, "tax": 20.2},
{"name": "Baz", "description": None, "price": 50.2, "tax": 10.5, "tags": []},
]这可能会做到这一点,调用端点应该返回:
$ curl http://127.0.0.1:8000/items | jq
{
"items": [
{
"name": "Foo",
"price": 50.2
},
{
"name": "Bar",
"description": "The bartenders",
"price": 62,
"tax": 20.2
},
{
"name": "Baz",
"description": null,
"price": 50.2,
"tax": 10.5,
"tags": []
}
]
}评论
如果Items只包含一个list of Item,我建议保持简单,然后返回List[Item] (使用pydantic的parse_obj_as):
from pydantic import parse_obj_as
# ...
@app.get("/items", response_model=List[Item], response_model_exclude_unset=True)
async def read_item():
return parse_obj_as(List[Item], itemslist)但是,请注意,在这种情况下,输出略有不同:
$ curl http://127.0.0.1:8000/items | jq
[
{
"name": "Foo",
"price": 50.2
},
{
"name": "Bar",
"description": "The bartenders",
"price": 62,
"tax": 20.2
},
{
"name": "Baz",
"description": null,
"price": 50.2,
"tax": 10.5,
"tags": []
}
]https://stackoverflow.com/questions/68977411
复制相似问题