Pub/sub aka listen/notify
PostgreSQL has a little-known but powerful publish-subscribe/listen-notify feature.
It's very useful for things doing things like task queues and event-driven architectures, while keeping everything within Postgres instead of needing to add a separate piece of infrastructure to your setup.
Conceptually it's pretty simple: One connection does a
listen on a channel, and waits for another connection to do a
notify on that channel.
Sending notifications is a one-liner: Just specify a channel name and optional payload string:
db = databaseci.db('example') db.notify('channel_name', 'payload')
Then any other code anywhere else can listen by creating a listening connection:
db = databaseci.db('example') with db.listen("channel_name") as listening:
And looping through notifications as they are received:
for n in db.notifications( listening ): print(n.channel) # channel_name print(n.payload) # payload
Listen on multiple channel by passing in a list:
with db.listen( ["channel1", "channel2"] ) as listening:
Set a timeout (returns
None on timeout):
for n in db.notifications( listening, timeout=5 ): if n is None: print('Timed out waiting for notifications.') break
Handle signals, for instance you may wish to catch a keyboard interrupt so you can print a friendly message or do other cleanup handling before exiting.
for n in db.notifications( listening, timeout=5, handle_signals=[signal.SIGINT] ): if isinstance(n, int): sig = signal.Signals(n) print('Interrupt caught, stopping.') break