也许我像往常一样错过了一些东西
from fastapi import FastAPI, status, HTTPException
@app.delete("/posts/{id}")
def delete_post(id: int):
try:
with psycopg.connect("host=localhost dbname=fastapi user=postgres password=postgres") as conn:
with conn.cursor() as cur:
deleted_post = cur.execute("DELETE FROM posts WHERE id = %s RETURNING *", [id]).fetchone()
conn.commit()
if deleted_post == None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Post with id: {id} was not found."
)
return {"message": deleted_post}
当我尝试删除或更新不存在的 id 时,它会识别:“if returned_post == None:”,但它总是返回状态 200 OK
您将所有代码都放在
try
块中,但没有显示 expect
块。我的猜测是,异常在您的 expect
块中以任意 JSON 形式返回,这就是状态代码不起作用的原因。