简体   繁体   English

如何更改获取列表的输出,或在 FastAPI 中使用备用序列化程序?

[英]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

Working Example工作示例

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.

相关问题 如何使用 FastAPI 设置 swagger ui 以在查询参数中使用列表字段 - How to set swagger ui to use list fields in query parameters with FastAPI 如何在python中获得以下输出 - How to get the following ouput in python Django Rest Framework Serializer关系:如何获取父级序列化器中所有子对象的列表? - Django Rest Framework Serializer Relations: How to get list of all child objects in parent's serializer? Web 用 Selenium 和 read_html 抓取 - 获取表格内容的更好方法? 如何使用列表 DataFrame 的输出? - Web scraping with Selenium & read_html - Better method to get table contents? How to work with ouput of a list DataFrame? 如何从输出中删除脏话列表 - How to remove a list of dirty words from ouput FastAPI - 如何在响应中使用 HTTPException? - FastAPI - How to use HTTPException in responses? 如何在 fastapi 中使用刷新令牌? - How to use refresh token with fastapi? 如何对列表中存在的列使用alter table drop columns? - How to use alter table drop columns for columns present in a list? 如何在 Django 中为 get 和 post 方法使用相同的序列化程序类? - How to use same serializer class for get and post method in Django? 如何获得 arrays 输出结果在括号中,如 [1][2][3] 到 [1 2 3] - How to get arrays that ouput result in brackets like [1][2][3] to [1 2 3]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM