在 Post 请求正文中发送列表值以验证 Pydantic 模型
sending a list value in a Post request's body to validate Pydantic model
我正在使用 FastAPI、Pydantic、SQLAlchemy 和 Postgres 构建接收 post 请求并将数据存储在数据库中的服务。 Pydantic 模型中有一个 List,如下所示:
from typing import List
from pydantic import BaseModel, Field
class Note(base model):
id: int
title: str
authors: List[str]
和table:
notes = Table(
"notes",
metadata,
Column("id", Integer, primary_key=True),
Column("title", String),
Column("authors", ARRAY(String(50), dimensions=3)),
)
这是我执行 post 请求的方式,当没有 List 值时:
def post(payload: Note):
query = questions.insert().values(title=payload.title)
return database.execute(query=query)
Post 请求正文:
{
"title": "some value"
}
而且效果很好。但是添加 List 值会因 Pydantic 的验证错误而中断它:
def post(payload: Note):
query = questions.insert().values(title=payload.title, authors=payload.authors)
return database.execute(query=query)
{
"title": "some value",
"authors": ["name1", "name2", "name3"]
}
value is not a valid list
type_error.list
如何更改 post 函数和请求正文,使其正常工作?
编辑:回溯:
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/uvicorn/protocols/http/httptools_impl.py", line 385, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/usr/lib/python3/dist-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
return await self.app(scope, receive, send)
File "/home/saeed/.local/lib/python3.8/site-packages/fastapi/applications.py", line 149, in __call__
await super().__call__(scope, receive, send)
File "/home/saeed/.local/lib/python3.8/site-packages/starlette/applications.py", line 102, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/saeed/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc from None
File "/home/saeed/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/home/saeed/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/home/saeed/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/home/saeed/.local/lib/python3.8/site-packages/starlette/routing.py", line 550, in __call__
await route.handle(scope, receive, send)
File "/home/saeed/.local/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle
await self.app(scope, receive, send)
File "/home/saeed/.local/lib/python3.8/site-packages/starlette/routing.py", line 41, in app
response = await func(request)
File "/home/saeed/.local/lib/python3.8/site-packages/fastapi/routing.py", line 204, in app
response_data = await serialize_response(
File "/home/saeed/.local/lib/python3.8/site-packages/fastapi/routing.py", line 126, in serialize_response
raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for Note
response
value is not a valid list (type=type_error.list)
我想通了。通过修复有错误的 respone_model
解决了问题,我为存储数据所做的一切都是正确的。
@router.post("/", response_model=Note, status_code=201)
def create_note(payload: Note):
note_id = post(payload)
response_object = {
"id": note_id,
"title": payload.title,
"authors": payload.authors,
}
return response_object
@router.get("/fetchusuarios", response_model=List[providers.schemas.User])
async def fetchall_users(db:Session=Depends(get_db)):
usuarios = db.query(models.usermodel.User).all()
return usuarios
我在使用 Django-Ninja(基于 FastAPI)时遇到了同样的错误。原来我的装饰器是这样的:
@router.get('/apartment-sale-hanoi/', response=List[ApartmentSaleHanoiSchema])
我通过从响应模型中删除 List
来修复 value is not a valid list (type=type_error.list)
,如下所示:
@router.get('/apartment-sale-hanoi/', response=ApartmentSaleHanoiSchema)
我返回的响应(显示为 JSON)是一个对象列表
response = ApartmentSaleHanoi.objects.all()
我正在使用 FastAPI、Pydantic、SQLAlchemy 和 Postgres 构建接收 post 请求并将数据存储在数据库中的服务。 Pydantic 模型中有一个 List,如下所示:
from typing import List
from pydantic import BaseModel, Field
class Note(base model):
id: int
title: str
authors: List[str]
和table:
notes = Table(
"notes",
metadata,
Column("id", Integer, primary_key=True),
Column("title", String),
Column("authors", ARRAY(String(50), dimensions=3)),
)
这是我执行 post 请求的方式,当没有 List 值时:
def post(payload: Note):
query = questions.insert().values(title=payload.title)
return database.execute(query=query)
Post 请求正文:
{
"title": "some value"
}
而且效果很好。但是添加 List 值会因 Pydantic 的验证错误而中断它:
def post(payload: Note):
query = questions.insert().values(title=payload.title, authors=payload.authors)
return database.execute(query=query)
{
"title": "some value",
"authors": ["name1", "name2", "name3"]
}
value is not a valid list
type_error.list
如何更改 post 函数和请求正文,使其正常工作?
编辑:回溯:
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/uvicorn/protocols/http/httptools_impl.py", line 385, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/usr/lib/python3/dist-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
return await self.app(scope, receive, send)
File "/home/saeed/.local/lib/python3.8/site-packages/fastapi/applications.py", line 149, in __call__
await super().__call__(scope, receive, send)
File "/home/saeed/.local/lib/python3.8/site-packages/starlette/applications.py", line 102, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/saeed/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc from None
File "/home/saeed/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/home/saeed/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/home/saeed/.local/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/home/saeed/.local/lib/python3.8/site-packages/starlette/routing.py", line 550, in __call__
await route.handle(scope, receive, send)
File "/home/saeed/.local/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle
await self.app(scope, receive, send)
File "/home/saeed/.local/lib/python3.8/site-packages/starlette/routing.py", line 41, in app
response = await func(request)
File "/home/saeed/.local/lib/python3.8/site-packages/fastapi/routing.py", line 204, in app
response_data = await serialize_response(
File "/home/saeed/.local/lib/python3.8/site-packages/fastapi/routing.py", line 126, in serialize_response
raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for Note
response
value is not a valid list (type=type_error.list)
我想通了。通过修复有错误的 respone_model
解决了问题,我为存储数据所做的一切都是正确的。
@router.post("/", response_model=Note, status_code=201)
def create_note(payload: Note):
note_id = post(payload)
response_object = {
"id": note_id,
"title": payload.title,
"authors": payload.authors,
}
return response_object
@router.get("/fetchusuarios", response_model=List[providers.schemas.User])
async def fetchall_users(db:Session=Depends(get_db)):
usuarios = db.query(models.usermodel.User).all()
return usuarios
我在使用 Django-Ninja(基于 FastAPI)时遇到了同样的错误。原来我的装饰器是这样的:
@router.get('/apartment-sale-hanoi/', response=List[ApartmentSaleHanoiSchema])
我通过从响应模型中删除 List
来修复 value is not a valid list (type=type_error.list)
,如下所示:
@router.get('/apartment-sale-hanoi/', response=ApartmentSaleHanoiSchema)
我返回的响应(显示为 JSON)是一个对象列表
response = ApartmentSaleHanoi.objects.all()