Last active
December 14, 2015 11:14
-
-
Save onjin/d1262b158f6a9bdb886a to your computer and use it in GitHub Desktop.
pubsub using postgres listen/notify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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