Last active
October 1, 2017 16:54
-
-
Save ingoogni/169a2b8b1e484c71c95c55a2da2a65f0 to your computer and use it in GitHub Desktop.
CherryPy PostgreSQL pgpubsub
This file contains hidden or 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
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