Created
November 13, 2016 17:54
-
-
Save ergo70/de7bf3bbcb84ed201d08f6b48a260363 to your computer and use it in GitHub Desktop.
psycopg2 asynchronous notifications w. 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
# -*- coding: utf-8 -*- | |
""" | |
Created on Sun Nov 13 00:00:06 2016 | |
@author: ergo | |
""" | |
import select | |
import psycopg2 | |
import psycopg2.extensions | |
import threading | |
def notify(conn): | |
print "Waiting for notifications on channel 'cats'" | |
while True: | |
if select.select([conn],[],[],1) != ([],[],[]): | |
conn.poll() | |
while conn.notifies: | |
notify = conn.notifies.pop(0) | |
print "Got NOTIFY:", notify.pid, notify.channel, notify.payload | |
print "Must refresh cache" | |
conn = psycopg2.connect("host=<host> dbname=<dbname> user=<user> password=<password>") | |
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) | |
curs = conn.cursor() | |
curs.execute("LISTEN cats;") | |
t = threading.Thread(target=notify, args=(conn,)) | |
t.start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment