This is the runnable version of the Postgres/WebSocket idea that I presented in my PyOhio talk Pushy Postgres and Python. It is a slightly updated version of Daniele Varrazzo's example code from his blog post PostgreSQL notifications with Psycopg2 and Eventlet. If you want to try it out yourself,
- Make sure you have a Postgres database you can connect to
Edit
pushdemo.py
and update the variabledsn
to point to your databasedsn = 'dbname=testdb user=postgres password=secret'
You do not need to create a separate database for this demo.
pip install psycopg2 eventlet
python pushdemo.py
- Open a browser to http://localhost:7000. You should see a stack of three small color bars.
Open a shell connection to the database:
psql testdb postgres
Notify!
NOTIFY data, 'blue'; NOTIFY data, 'green';
The only significant change I made to the original demo is on line 35:
ws.send(unicode(n.payload))
I added the Unicode conversion due to a defect in Eventlet's API: without this conversion, Eventlet treats the payload as binary, which the client side of the WebSocket is not prepared to handle.
The demo uses Eventlet's trampoline
__ instead of the standard library select
__ call that I presented in the case study, so the blocking call:
select.select([conn], [], [], 10) != ([], [], [])
is spelled with the Eventlet-specific (line 20):
trampoline(cnn, read=True)