FastAPI Return删除的记录数
FastAPI Return the number of deleted records
在 FastAPI 中,我想 return 删除的行数。
我正在尝试下面的代码,但没有' return 号码。
@app.delete("/remove/{id}", status_code=status.HTTP_204_NO_CONTENT)
def remove(id, db: Session = Depends(get_db)):
effected_rows = db.query(models.Blog).filter(models.Blog.id == id).delete()
if effected_rows == 0:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
else:
db.commit()
return {
"detail": effected_rows
}
我想要类似的更新。
我假设您正在使用 SQLAlchemy。我还假设 models.Blog.id
是您的主键。
可以省略delete()
部分,以后再做。此外,您可以使用 get(identifier)
从 DB 获取博客。因为当博客不存在时你会得到 404 或者如果博客存在时你会得到 200(或其他),你也可以省略 return
部分,留下这个:
blog = db.query(models.Blog).get(id)
if blog is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
else:
db.delete(blog)
db.commit()
在 FastAPI 中,我想 return 删除的行数。
我正在尝试下面的代码,但没有' return 号码。
@app.delete("/remove/{id}", status_code=status.HTTP_204_NO_CONTENT)
def remove(id, db: Session = Depends(get_db)):
effected_rows = db.query(models.Blog).filter(models.Blog.id == id).delete()
if effected_rows == 0:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
else:
db.commit()
return {
"detail": effected_rows
}
我想要类似的更新。
我假设您正在使用 SQLAlchemy。我还假设 models.Blog.id
是您的主键。
可以省略delete()
部分,以后再做。此外,您可以使用 get(identifier)
从 DB 获取博客。因为当博客不存在时你会得到 404 或者如果博客存在时你会得到 200(或其他),你也可以省略 return
部分,留下这个:
blog = db.query(models.Blog).get(id)
if blog is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
else:
db.delete(blog)
db.commit()