I have this code for delete operation on a Postgresql DB:
JavaScript
x
11
11
1
@app.delete("/posts/{id}", status_code=status.HTTP_204_NO_CONTENT)
2
def delete_post(id: int):
3
print("ID IS ",id)
4
cursor.execute("""DELETE FROM public."Posts" WHERE id = %s""", (str(id),))
5
deleted_post = cursor.fetchone() <--- Showing error for this line
6
conn.commit()
7
if deleted_post is None:
8
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
9
detail=f"Post with {id} not found")
10
return Response(status_code=status.HTTP_204_NO_CONTENT)
11
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:
JavaScript
1
12
12
1
File "D:Python ProjectsFASTAPIvenvlibsite-packagesanyioto_thread.py", line 31, in run_sync
2
return await get_asynclib().run_sync_in_worker_thread(
3
File "D:Python ProjectsFASTAPIvenvlibsite-packagesanyio_backends_asyncio.py", line 937, in run_sync_in_worker_thread
4
return await future
5
File "D:Python ProjectsFASTAPIvenvlibsite-packagesanyio_backends_asyncio.py", line 867, in run
6
result = context.run(func, *args)
7
File "D:Python ProjectsFASTAPI.appmain.py", line 80, in delete_post
8
deleted_post = cursor.fetchone()
9
File "D:Python ProjectsFASTAPIvenvlibsite-packagespsycopg2extras.py", line 86, in fetchone
10
res = super().fetchone()
11
psycopg2.ProgrammingError: no results to fetch
12
What really is happening here??
Advertisement
Answer
The DELETE
query does not return any results, thus the fetchone()
call raises an error. Try adding a RETURNING
clause:
JavaScript
1
11
11
1
@app.delete("/posts/{id}", status_code=status.HTTP_204_NO_CONTENT)
2
def delete_post(id: int):
3
print("ID IS ",id)
4
cursor.execute("""DELETE FROM public."Posts" WHERE id = %s RETURNING id""", (str(id),))
5
deleted_post = cursor.fetchone() <--- Showing error for this line
6
conn.commit()
7
if deleted_post is None:
8
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
9
detail=f"Post with {id} not found")
10
return Response(status_code=status.HTTP_204_NO_CONTENT)
11