[英]How to alter the ouput of a get list, or use an alternate serializer in FastAPI?
I'm trying to alter the content of a list view on FastAPI, depending on a get parameter.我正在尝试根据 get 参数更改 FastAPI 上列表视图的内容。 As the format is defined by a pydantic model, how can I customize it (or use an alternative model from within the view)?
由于格式由 pydantic model 定义,我如何自定义它(或在视图中使用替代 model)?
Here's my view:这是我的观点:
from fastapi_pagination import Page, Params, paginate
from pydantic import BaseModel
from sqlalchemy.orm import Session
class EventSerializer(BaseModel):
id: str
# ...
class EventAttendeeSerializer(BaseModel):
id: str
event: str # contains the event UUID
# ...
class Config:
orm_mode = True
@api.get("/", response_model=Page[EventAttendeeSerializer])
async def get_list(db: Session, pagination: Params = Depends(), extend: str = None):
objects = db.query(myDbModel).all()
if "event" in extend.split(","):
# return EventSerializer for each object instead of id
return paginate(objects, pagination)
At runtime, it would work like this:在运行时,它会像这样工作:
GET /v1/event-attendees/
{
"items": [
{
"id": <event_attendee_id>,
"event": <event_id>,
}
],
"total": 1,
"page": 1,
"size": 50,
}
GET /v1/event-attendees/?extend=event
{
"items": [
{
"id": <event_attendee_id>,
"event": {
"id": <event_id>,
# ...
}
}
],
"total": 1,
"page": 1,
"size": 50,
}
I searched for some kind of hooks in the pydantic and FastAPI docs and source code, but did not find anything relevant.我在 pydantic 和 FastAPI 文档和源代码中搜索了某种挂钩,但没有找到任何相关内容。 Anyone can help please?
有人可以帮忙吗?
You can decalre a response_model
using Union
(of two types) and return the model your wish if a condition is met.您可以使用
Union
(两种类型)对response_model
进行decalre,并在满足条件时返回您希望的 model。 Since you are returning a list of objects/models, you can have response_model
declared as a List
of Union
.由于您要返回对象/模型列表,因此可以将
response_model
声明为Union
List
。
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Union
class Simple(BaseModel):
id: int
class Specific(Simple):
description: str
RESULT = {
'id': 1,
'description': 'test'
}
app = FastAPI()
@app.get('/results', response_model=List[Union[Specific, Simple]])
def get_results(specific: bool = False):
if specific:
results = [Specific(**RESULT)] * 2
else:
results = [Simple(**RESULT)] * 2
return results
Using FastAPI 0.89.0+ , you can alternatively declare the return type / response_model
in the function return type annotation , for instance:使用 FastAPI 0.89.0+ ,您可以选择在 function 返回类型注释中声明返回类型 /
response_model
,例如:
@app.get('/results')
def get_results(specific: bool = False) -> List[Union[Specific, Simple]]:
if specific:
# ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.