我有这个功能和其他类似功能(有同样的问题):
async def update_row_by_id(db: Session, tableOrm, tableModel, object_id:int):
obj_update = fetch_object_by_id(db, tableOrm, object_id)
for field in tableModel.model_dump(exclude_unset=True):
setattr(obj_update, field, getattr(tableModel, field))
try:
if(obj_update.updated_by is None):
obj_update.updated_by = db.query(literal_column("current_user"))
obj_update.updated_at = datetime.now()
except AttributeError:
pass
try:
db.commit()
except (ProgrammingError,IntegrityError, PendingRollbackError) as e:
db.rollback()
print(e._message())
raise HTTPException(status_code = status.HTTP_406_NOT_ACCEPTABLE, detail = e._message())
return obj_update
它的名字是这样的:
@router.put(urlIdRoute, status_code=200)
async def crud_update_by_id(obj_id:int, obj_model:modelBase):
db = SessionLocal()
try:
res = await update_row_by_id(db, orm, obj_model, obj_id)
return res
finally:
db.close()
问题是,在 fastapi/docs 中,当我测试此端点时,它返回 {},但数据已提交到数据库中。 另一个问题/解决方案是:如果我在 return 语句之前放置 print(obj_update) ,端点将正确返回数据。
为什么我的代码受到 print 语句的影响以及如何修复此问题而不需要放置 print(obj_update)?
我尝试在获取数据时创建async/await,但出现其他错误,这是object_fetch函数:
def fetch_object_by_id(db: Session, tableOrm, object_id:int):
obj = db.scalar(select(tableOrm).filter_by(id = object_id))
if obj is None:
raise common_404_exception(tableOrm.__tablename__, object_id)
return obj
您的
fetch_object_by_id
需要使用async/await来处理数据库调用
async def fetch_object_by_id(db: Session, tableOrm, object_id:int):
obj = await db.scalar(select(tableOrm).filter_by(id = object_id))
if obj is None:
raise common_404_exception(tableOrm.__tablename__, object_id)
return obj
然后在您的路线中使用
obj_update = await fetch_object_by_id(db, tableOrm, object_id)