postgresql FASTAPI删除操作出现内部服务器错误

axkjgtzd  于 2022-12-29  发布在  PostgreSQL
关注(0)|答案(2)|浏览(137)

我有这个代码删除操作的Postgresql数据库:

@app.delete("/posts/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_post(id: int):
    print("ID IS ",id)
    cursor.execute("""DELETE FROM public."Posts" WHERE id = %s""", (str(id),))
    deleted_post = cursor.fetchone()  <--- Showing error for this line
    conn.commit()
    if deleted_post is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"Post with {id} not found")
    return Response(status_code=status.HTTP_204_NO_CONTENT)

创建和读取操作运行良好。如果我传递一个现有的或不存在的id来删除,我会得到一个500内部服务器错误。但是行确实会从表中删除。
如果我注解这一行deleted_post = cursor.fetchone(),它工作正常。
下面是错误追溯:

File "D:\Python Projects\FASTAPI\venv\lib\site-packages\anyio\to_thread.py", line 31, in run_sync
    return await get_asynclib().run_sync_in_worker_thread(
  File "D:\Python Projects\FASTAPI\venv\lib\site-packages\anyio\_backends\_asyncio.py", line 937, in run_sync_in_worker_thread
    return await future
  File "D:\Python Projects\FASTAPI\venv\lib\site-packages\anyio\_backends\_asyncio.py", line 867, in run
    result = context.run(func, *args)
  File "D:\Python Projects\FASTAPI\.\app\main.py", line 80, in delete_post
    deleted_post = cursor.fetchone()
  File "D:\Python Projects\FASTAPI\venv\lib\site-packages\psycopg2\extras.py", line 86, in fetchone
    res = super().fetchone()
psycopg2.ProgrammingError: no results to fetch

这里到底发生了什么??

z0qdvdin

z0qdvdin1#

DELETE查询未返回任何结果,因此fetchone()调用引发错误。请尝试添加RETURNING子句:

@app.delete("/posts/{id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_post(id: int):
    print("ID IS ",id)
    cursor.execute("""DELETE FROM public."Posts" WHERE id = %s RETURNING id""", (str(id),))
    deleted_post = cursor.fetchone()  <--- Showing error for this line
    conn.commit()
    if deleted_post is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
                            detail=f"Post with {id} not found")
    return Response(status_code=status.HTTP_204_NO_CONTENT)
rdrgkggo

rdrgkggo2#

Pawe已经发现这个问题,但我强烈建议您使用ORM,它简化的事情:

def delete_post(id: int, db: Session = Depends(get_db)):
    post = db.query(Posts).get(id)
    if post is None:
        raise
    post.delete() # depends on session settings you need to do db.commit() or not
    return Response()

有关依赖关系设置,请查看此处:

相关问题