[英]Python/Pydantic iterate over post body with multiple items
I'm new to pydantic...I want to send (via post) multiple json entries.我是 pydantic 的新手……我想发送(通过邮寄)多个 json 条目。 Is this
这是
__root__
thingy the correct way?正确的方法? How can I iterate the single entries from the post body?
如何从帖子正文中迭代单个条目?
import uvicorn
from pydantic import BaseModel
from fastapi import FastAPI
from typing import List
app = FastAPI()
class Books(BaseModel):
title: str
subtitle: str
description: str
class BooksList(BaseModel):
__root__: List[Books]
@app.post("/book_data")
def book_data(data: BooksList):
# iterate over the single entries and insert it to my database
return 'foo'
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
And this is the postman body:这是 postman 主体:
[
{
"title": "title1",
"subtitle": "sub1",
"description": "desc1"
},
{
"title": "title2",
"subtitle": "sub2",
"description": "desc2"
}
]
You can iterate it via data.__root__
您可以通过
data.__root__
对其进行迭代
for item in data.__root__:
do(item)
Or you can define own __iter__
and __getitem__
functions and iterate over it:或者您可以定义自己的
__iter__
和__getitem__
函数并对其进行迭代:
class BooksList(BaseModel):
__root__: List[Books]
def __iter__(self):
return iter(self.__root__)
def __getitem__(self, item):
return self.__root__[item]
#...
for item in data:
do(item)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.