Today we’re pleased to introduce Django EventStream, a module that provides Server-Sent Events capability to your Django server application. It relies on Pushpin or Fanout Cloud to manage the client connections. Events can optionally be persisted to your database, for highly reliable delivery.

Basic usage

Simply add django_eventstream to your server project, set up Pushpin or Fanout Cloud in front of it, and you’re done.

A client can then connect with a GET request:

GET /events/?channel=test HTTP/1.1
Host: api.example.com
Accept: text/event-stream

The client would receive a streaming HTTP response with content looking like this:

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Connection: Transfer-Encoding
Content-Type: text/event-stream

event: stream-open
data:

event: message
id: test:1
data: {"foo": "bar"}

event: message
id: test:2
data: {"bar": "baz"}

Server-Sent Events streams are easy to consume in browsers, using the EventSource JavaScript API. For environments without a native client-side library, the protocol is straightforward to parse (just lines).

To send data to clients, call send_event:

from django_eventstream import send_event

send_event('test', 'message', {'text': 'hello world'})

Proxying for the win

Fanout Cloud already offers a Bayeux publish-subscribe service for easy JSON messaging, and of course there are plenty of other publish-subscribe messaging systems out there to choose from. What’s different about Django EventStream is that it’s based on our Custom API / GRIP proxy architecture, which enables additional benefits:

  • Reuse existing authentication. If you authenticate clients using cookies or tokens, you can authenticate streaming connections the same way.

  • Robust authorization. Channel access can be revoked while a user is connected and they will be disconnected. If there is an error communicating this change to the proxy, the proxy will eventually reconfirm the authorization with your backend server. If your server can’t be reached, the client will be disconnected.

  • High reliability. If clients get disconnected or server components crash, our proxy is able to query your backend for missed messages to ensure they are correctly delivered. Even if your server app crashes mid-publish, the message will still eventually be delivered because it is recorded durably to your database prior to publishing.

What are you waiting for? Get yourself a Fanout Cloud account and start pushing data reliably with Django EventStream today.