Skip to content

Instantly share code, notes, and snippets.

@ingoogni
Last active October 1, 2017 16:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ingoogni/169a2b8b1e484c71c95c55a2da2a65f0 to your computer and use it in GitHub Desktop.
Save ingoogni/169a2b8b1e484c71c95c55a2da2a65f0 to your computer and use it in GitHub Desktop.
CherryPy PostgreSQL pgpubsub
import threading
import pgpubsub
import cherrypy
from cherrypy.process import plugins
class PGrepub(plugins.SimplePlugin):
"""
Plugin that listens to Postresql notification channels and publishes
the payload unmodified to a channel on the CherryPy bus.
Requires psycopg2 and pgpubsub https://pypi.python.org/pypi/pgpubsub/
channels: a dictionary holding the conversion of channel names,
{PG notify channel : CP publish channel}
"""
thread = None
def __init__(self, bus, dsn, channels):
plugins.SimplePlugin.__init__(self, bus)
self.pubsub = pgpubsub.connect(dsn)
self.channels = channels
def start(self):
if not self.thread:
self.bus.log('Starting up PGrepub')
self.thread = threading.Thread(target=self.run)
self.thread.start()
def stop(self):
if self.thread:
self.bus.log('Shut down PGrepub')
self.thread.join()
def run(self):
for channel in self.channels:
self.pubsub.listen(channel)
for event in self.pubsub.events(select_timeout=1):
cherrypy.engine.publish(self.channels[event.channel], event.payload)
dsn = "dbname=YourDB user=PasMoi password=Super@Secret"
channels = {'pg_foo': 'cp_foo', 'pg_bar': 'cp_bar'}
PGrepub(cherrypy.engine, dsn, channels).subscribe()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment