首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在FastAPI响应中使用字段别名而不是名称返回Pydantic模型?

如何在FastAPI响应中使用字段别名而不是名称返回Pydantic模型?
EN

Stack Overflow用户
提问于 2022-11-06 00:56:25
回答 1查看 127关注 0票数 1

我的FastAPI调用没有以正确的Response模型格式返回数据。它以数据库模型格式返回数据。

我的数据库模型:

代码语言:javascript
运行
复制
class cat(DBConnect.Base):
     __tablename__ = 'category'
     __table_args__ = {"schema": SCHEMA}
     cat_id = Column('cat_id',UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
     cat_desc = Column('cat_desc', TEXT, nullable=True)
     cat_h__l_name = Column('cat_h_l_name', TEXT, nullable=True)

我的勾股模型:

代码语言:javascript
运行
复制
claaa CamelModel(BaseModel):
    class config:
         alias_generator = to_camel
         allow_population_by_field_name = True

Class cat(CamelModel):
     cat_id =Field(alais='CatID', readonly=True)
     cat_description =Field(alias='CatDescription')
     cat_h__l_name = Field(alias='CatName')
     
    class config:
       orm_mode= True

我的API CAll:

代码语言:javascript
运行
复制
@router.patch('/cat/{id}/', response_model = 'cat')
def update_cat(response= Response, params: updatecat = Depends(updatecat)):
    response_obj = { resonse_code: status.HTTP_200_OK, 
    response_obj : {}    
    }
    
    response_obj = session.query() # It is returning the correct data from the database
    response.status_code = response_obj['response_code']
    
    return JSONResponse(response_obj['response_obj'], status_code = response_obj['response_code'])

以下列格式获得响应:

代码语言:javascript
运行
复制
     cat_id = 'some uuid'
     cat_desc = 'desc'
     cat_h__l_name = 'some h_l_name'

但我希望回复应该以以下格式返回:

代码语言:javascript
运行
复制
CatID = 'some uuid'
CatDescription ='' some description'
CatName = 'Some cat name'

这段代码没有出现任何错误(我已经输入了它,因此可能出现了缩进或拼写错误)。唯一的问题是API没有以正确的格式返回数据。我被困在上面一段时间了。我是FastAPI的新手。请帮帮我。

EN

回答 1

Stack Overflow用户

发布于 2022-11-06 06:23:47

可以将response_model_by_alias=True添加到端点。这在文档中提到了这里

代码语言:javascript
运行
复制
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


def to_camel(string: str) -> str:
    return ''.join(word.capitalize() for word in string.split('_'))

class Item(BaseModel):
    name: str
    language_code: str
    
    class Config:
        alias_generator = to_camel
        allow_population_by_field_name = True    
            

fake_db = [
    Item(name='foo', language_code='en'),
    Item(name='bar', language_code='fr')
]


@app.get('/item/{item_id}', response_model=Item, response_model_by_alias=True)
def create_item(item_id: int):
    return fake_db[item_id]

但是,由于您似乎是在返回端点中的JSONResponse而不是模型,所以设置response_model_by_alias=True不会有任何效果。因此,可以使用Pydantic的model.dict(...)将模型转换为字典,并将by_alias参数设置为True

另外,如果您有不能序列化的数据类型(如datetimeUUID等),则为datetime。对于这些情况,您可以在将数据传递给响应之前使用jsonable_encoder来转换数据。jsonable_encoder将确保不可序列化的对象将转换为str

代码语言:javascript
运行
复制
from fastapi.responses import JSONResponse
from fastapi.encoders import jsonable_encoder

@app.get('/item/{item_id}')
def create_item(item_id: int):
    return JSONResponse(jsonable_encoder(fake_db[item_id].dict(by_alias=True)), status_code=200)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74332593

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档