[Twisted-Python] adbapi / Postgres : LISTEN/NOTIFY and RealDictCursor

Tobias Oberstein tobias.oberstein at tavendo.de
Thu Nov 3 18:18:03 EDT 2011


Ok, should anyone else need this, here is working code:

 
class PostgresListenService(twisted.application.service.Service):
   """
   PostgreSQL LISTEN/NOTIFY as Twisted service.
   
   http://initd.org/psycopg/docs/advanced.html#asynchronous-notifications
   """

   def __init__(self, dsn, channel, timeout = 1):
      self.dsn = dsn
      self.channel = channel
      self.timeout = 1

   def notify(self, channel, payload):
      log.msg("NOTIFY on channel %s with payload %s, delivered on thread %s" % (channel, payload, thread.get_ident()))

   def run(self):
      log.msg("LISTEN on channel %s, running on thread %s" % (self.channel, thread.get_ident()))
      conn = psycopg2.connect(self.dsn)
      conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
      curs = conn.cursor()
      curs.execute("LISTEN %s;" % self.channel)
      while not self.stopped:
         if select.select([conn], [], [], self.timeout) == ([], [], []):
            pass
         else:
            conn.poll()
            while conn.notifies:
               notify = conn.notifies.pop()
               reactor.callFromThread(self.notify, notify.channel, notify.payload)

   def startService(self):
      self.stopped = False
      reactor.callInThread(self.run)
      Service.startService(self)

   def stopService(self):
      self.stopped = True
      Service.stopService(self)




More information about the Twisted-Python mailing list