Skip to content

Instantly share code, notes, and snippets.

@onjin
Last active December 14, 2015 11:14
Show Gist options
  • Save onjin/d1262b158f6a9bdb886a to your computer and use it in GitHub Desktop.
Save onjin/d1262b158f6a9bdb886a to your computer and use it in GitHub Desktop.
pubsub using postgres listen/notify
CREATE OR REPLACE FUNCTION object_notify() RETURNS trigger AS $$
DECLARE
BEGIN
PERFORM pg_notify('object_updated',CAST(NEW.id AS text));
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER object_post_insert_notify AFTER UPDATE ON objects FOR EACH ROW EXECUTE PROCEDURE object_notify();
#!/usr/bin/env python
import psycopg2
import select
DSN = 'postgres://postgres@localhost:5433/pubsub'
def handle_notification(notify):
print(notify)
conn = psycopg2.connect(DSN)
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
curs = conn.cursor()
curs.execute("LISTEN test;")
while True:
if select.select([conn],[],[],5) == ([],[],[]):
pass
else:
conn.poll()
while conn.notifies:
notify = conn.notifies.pop()
handle_notification(notify)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment