pgnotify: A python library to easily LISTEN to PostgreSQL NOTIFY notifications
Example
LISTEN to and process NOTIFY events with a simple for
loop, like so:
from pgnotify import await_pg_notifications
for notification in await_pg_notifications(
'postgresql:///example',
['channel1', 'channel2']):
print(notification.channel)
print(notification.payload)
Install
Installable with any python package manager from the python package index, eg:
pip install pgnotify
All the bells and whistles
You can also handle timeouts and signals, as in this more fully-fleshed example:
import signal
from pgnotify import await_pg_notifications, get_dbapi_connection
CONNECT = "postgresql:///example"
e = get_dbapi_connection(CONNECT)
SIGNALS_TO_HANDLE = [signal.SIGINT, signal.SIGTERM]
for n in await_pg_notifications(
e,
["hello", "hello2"],
timeout=10,
yield_on_timeout=True,
handle_signals=SIGNALS_TO_HANDLE,
):
if isinstance(n, int):
sig = signal.Signals(n)
print(f"handling {sig.name}, stopping")
break
elif n is None:
print("timeout, continuing")
else:
print((n.pid, n.channel, n.payload))
Further documentation to come.