Skip to content

Instantly share code, notes, and snippets.

@JirkaChadima
Last active June 30, 2017 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JirkaChadima/ef2ef42c00489e2db42b7eac4535063d to your computer and use it in GitHub Desktop.
Save JirkaChadima/ef2ef42c00489e2db42b7eac4535063d to your computer and use it in GitHub Desktop.
listen-notify-backend
from eventlet.hubs import trampoline
def start_listening(queue):
"""Connects to PgSQL and listens to notifications, inspired by http://initd.org/psycopg/articles/2010/12/01/postgresql-notifications-psycopg2-eventlet/"""
if not queue:
return
connection = psycopg2.connect(DSN)
cursor = connection.cursor()
cursor.execute("LISTEN field_value_change")
while True:
trampoline(connection, read=True)
connection.poll()
while connection.notifies:
notify = connection.notifies.pop()
queue.put(json.loads(notify.payload))
def emitter(queue):
"""Listens to queued events and emits data_changed broadcast event to a socket"""
while True:
element = queue.get()
socketio.emit('data_changed', {'data': {'name': element['field'], 'value': element['value']}}, broadcast=True)
# ...
dbThread = None
qThread = None
@socketio.on('connect')
def connect():
"""On first socket.io connection registers the database listener and value emitter"""
global dbThread
global qThread
q = eventlet.Queue()
if dbThread is None:
dbThread = socketio.start_background_task(target=start_listening, queue=q)
qThread = socketio.start_background_task(target=emitter, queue=q)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment