简体   繁体   中英

FASTAPI Delete Operation giving Internal server error

I have this code for delete operation on a Postgresql DB:

@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)

The create and read operations work fine. If I pass an existing or a non-exsiting id to delete, I get a 500 Internal Server error. The row does get deleted from the table though.

If I comment this line deleted_post = cursor.fetchone() , it works okay.

Here is the error traceback:

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

What really is happening here??

The DELETE query does not return any results, thus the fetchone() call raises an error. Try adding a RETURNING clause:

@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)

Paweł already discover the issue, but I would highly recommend you to user ORM, it simplify the things:

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()

For dependency setup, look here :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM