Skip to content

Instantly share code, notes, and snippets.

@pkese
Created May 25, 2012 21:36
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pkese/2790749 to your computer and use it in GitHub Desktop.
Save pkese/2790749 to your computer and use it in GitHub Desktop.
Django&PostgreSQL: LISTEN + NOTIFY = Async notifications
##########################################################
# django postgres polling - LISTEN
import psycopg2.extensions
import select
from django.db import connection
crs = connection.cursor() # get the cursor and establish the connection.connection
pg_con = connection.connection
pg_con.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
crs.execute('LISTEN test;');
print "Waiting for notifications on channel 'test'"
while 1:
if select.select([pg_con],[],[],5) == ([],[],[]):
print "Timeout"
else:
pg_con.poll()
while pg_con.notifies:
notify = pg_con.notifies.pop()
print "Got NOTIFY:", `notify`
##########################################################
# django postgres polling - NOTIFY
from django.db import connection
import psycopg2.extensions
crs = connection.cursor() # get the cursor and establish the connection.connection
connection.connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
crs.execute('NOTIFY test;');
crs.execute('SELECT pg_sleep(6); NOTIFY test;');
@jakedormer
Copy link

Hi there,

I wonder if you could explain to me how this works?

I am currently using a django to build a web app, whilst using psycopg2 to do bulk inserts to the database. However, when using INSERT, no signals are sent to django for me to act on. I wondered if you had any advice?

@hmassonn
Copy link

hmassonn commented Oct 2, 2019

hi jake, i've just see in the doc the duo LISTEN/NOTIFY work together, INSERT is good but if you want the listener know the INSERT is effective the process which INSERT need to NOTIFY too, i hope this help

@gilillo32
Copy link

Where in the Django project is this script suposed to live?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment