From: Daniele Varrazzo Date: Mon, 2 May 2022 00:37:00 +0000 (+0200) Subject: docs: add hint about using add_signal_handler() to interrupt async queries X-Git-Tag: 3.1~124 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=f77b7c00912fc37d041d13052276879726ff0189;p=thirdparty%2Fpsycopg.git docs: add hint about using add_signal_handler() to interrupt async queries Courtesy @gjcarneiro, thank you! --- diff --git a/docs/advanced/async.rst b/docs/advanced/async.rst index 7269bd73a..db0b341a4 100644 --- a/docs/advanced/async.rst +++ b/docs/advanced/async.rst @@ -106,6 +106,36 @@ Note that the `AsyncConnection.cursor()` function is not an `!async` function you can use the normal `async with` context manager. +.. index:: Ctrl-C + +.. _async-ctrl-c: + +Interrupting async operations using Ctrl-C +------------------------------------------ + +If a long running operation is interrupted by a Ctrl-C on a normal connection +running in the main thread, the operation will be cancelled and the connection +will be put in error state, from which can be recovered with a normal +`~Connection.rollback()`. + +If the query is running in an async connection, a Ctrl-C will be likely +intercepted by the async loop and interrupt the whole program. In order to +emulate what normally happens with blocking connections, you can use +`asyncio's add_signal_handler()`__, to call `Connection.cancel()`: + +.. code:: python + + import asyncio + import signal + + async with await psycopg.AsyncConnection.connect() as conn: + loop.add_signal_handler(signal.SIGINT, conn.cancel) + ... + + +.. __: https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.add_signal_handler + + .. index:: pair: Asynchronous; Notifications pair: LISTEN; SQL command diff --git a/docs/news.rst b/docs/news.rst index 24c9cb1ae..1ed40085d 100644 --- a/docs/news.rst +++ b/docs/news.rst @@ -54,7 +54,7 @@ Psycopg 3.0.10 ^^^^^^^^^^^^^^ - Leave the connection in working state after interrupting a query with Ctrl-C - (currently only for sync connections, :ticket:`#231`). + (:ticket:`#231`). - Fix `Cursor.description` after a COPY ... TO STDOUT operation (:ticket:`#235`). - Fix building on FreeBSD and likely other BSD flavours (:ticket:`#241`).