[英]return pydantic model with field names instead of alias as fastapi response
[英]How to return Pydantic model using Field aliases instead of names in FastAPI?
我的 FastAPI 调用没有以正确的Response
模型格式返回数据。 它以数据库模型格式返回数据。
我的数据库模型:
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)
我的 Pydantic 模型:
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 调用:
@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'])
以以下格式获取响应:
cat_id = 'some uuid'
cat_desc = 'desc'
cat_h__l_name = 'some h_l_name'
但我希望响应应以以下格式返回:
CatID = 'some uuid'
CatDescription ='' some description'
CatName = 'Some cat name'
这段代码没有给出任何错误(我已经输入了它,所以可能是一些缩进或拼写错误)。 唯一的问题是 API 没有以正确的格式返回数据。 我已经坚持了一段时间。 我是 FastAPI 的新手。 请帮我。
您可以将response_model_by_alias=True
添加到端点。 这是在文档中提到的。
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
。
附带说明一下,如果您的数据类型(例如datetime
、 UUID
等)无法序列化,则不能在不先将其转换为dict
的情况下将 Pydantic 模型放入JSONResponse
中。 对于这些情况,您可以在将数据传递给响应之前使用jsonable_encoder
来转换数据。 jsonable_encoder
将确保不可序列化的对象将被转换为str
。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.