Hi,
I have a custom method on my model manager that allows me to listen for notifications from modifications on the DB using postgreSQL. A short version of this code looks like this:
def listen_for_notify(self):
import select
import psycopg2
import psycopg2.extensions
from django.conf import settings
db_data = settings.DATABASES['default']
listened = None
returned_empty = None
search_timeout = 15
conn = psycopg2.connect(dbname=db_data['NAME'], user=db_data['USER'], password=db_data['PASSWORD'], host=db_data['HOST'], port=db_data['PORT'])
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
curs = conn.cursor()
curs.execute("LISTEN default;")
timeout = timezone.now() + timezone.timedelta(0, search_timeout)
while timezone.now() < timeout:
time_diff = timeout - timezone.now()
if select.select([conn], [], [], float(time_diff.seconds)) == ([], [], []):
listened = False
timeout = timezone.now()
else:
conn.poll()
while conn.notifies:
notify = conn.notifies.pop(0)
if notify.payload == "notified":
listened = True
returned_empty = False
timeout = timezone.now()
if notify.payload == 'search request returned empty':
listened = True
returned_empty = True
timeout = timezone.now()
curs.close()
conn.close()
return listened, returned_empty
It would be really nice if instead of using the psycopg2 library, I could use only django.db. Something like this:
def listen_for_notify(self):
from django.db import connection as conn
listened = None
returned_empty = None
search_timeout = 15
with conn.cursor() as curs
timeout = timezone.now() + timezone.timedelta(0, search_timeout)
while timezone.now() < timeout:
time_diff = timeout - timezone.now()
if select.select([conn], [], [], float(time_diff.seconds)) == ([], [], []):
listened = False
timeout = timezone.now()
else:
conn.poll()
while conn.notifies:
notify = conn.notifies.pop(0)
if notify.payload == "notified":
listened = True
returned_empty = False
timeout = timezone.now()
if notify.payload == 'search request returned empty':
listened = True
returned_empty = True
timeout = timezone.now()
return listened, returned_empty
I tried out the solution above using django.db, but it doesn't work because the django.db.connection object don't have a fileno() method.
Is this currently not supported or am I missing something? I though that the django.db is kind of just a wrapper around the actual psycopg2 library. So I wonder why I can't use the fileno() method on it.