我的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)
我的勾股模型:
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:
@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的新手。请帮帮我。
发布于 2022-11-06 06:23:47
可以将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
等),则为datetime
。对于这些情况,您可以在将数据传递给响应之前使用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)
https://stackoverflow.com/questions/74332593
复制相似问题