GithubHelp home page GithubHelp logo

sjtgs / django-eventstream Goto Github PK

View Code? Open in Web Editor NEW

This project forked from fanout/django-eventstream

0.0 2.0 0.0 96 KB

Reliable, multi-channel Server-Sent Events for Django, using Pushpin or Fanout Cloud

License: MIT License

Python 51.51% JavaScript 48.49%

django-eventstream's Introduction

Django EventStream

Django EventStream provides an API endpoint for your Django application that can push data to connected clients. It relies on Pushpin or Fanout Cloud to manage the connections. Data is sent using the Server-Sent Events protocol (SSE), in which data is streamed over a never-ending HTTP response.

For example, you could create an endpoint, /events/, that a client could connect to 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"}

Features:

  • Easy to consume from browsers or native applications.
  • Highly reliable. Events can be persisted to your database, so clients can recover if they get disconnected.
  • Set per-user channel permissions.
  • Clean API contract that could be exposed to third parties if desired.

Setup

Install this module:

pip install django-eventstream

Then a few changes need to be made to settings.py.

Add the GripMiddleware:

MIDDLEWARE = [
    'django_grip.GripMiddleware',
    ...
]

Set GRIP_URL with your Pushpin or Fanout Cloud settings:

# pushpin
GRIP_URL = 'http://localhost:5561'
# fanout cloud
GRIP_URL = 'http://api.fanout.io/realm/your-realm?iss=your-realm&key=base64:your-realm-key'

Add the django_eventstream app:

INSTALLED_APPS = [
    ...
    'django_eventstream',
]

Add an endpoint in urls.py:

from django.conf.urls import url, include
import django_eventstream

urlpatterns = [
    ...
    url(r'^events/', include(django_eventstream.urls)),
]

That's it! Clients can now connect to the /events/ endpoint and get a stream.

To send data to clients, call send_event:

from django_eventstream import send_event

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

The first argument is the channel to send on, the second is the event type, and the third is the event data. The data will be JSON-encoded using DjangoJSONEncoder.

Local development

If you're developing locally and want to test with Fanout Cloud, we recommend using ngrok to register a public host that routes to your local instance.

As a convenience, this module comes with a Django command runserver_ngrok that acts like runserver except it additionally configures your Fanout Cloud realm to use a detected tunnel as the origin server.

From a separate shell, run ngrok:

ngrok http 8000

Then run the runserver_ngrok command:

python manage.py runserver_ngrok

You should see output like this:

Setting ngrok tunnel 4f91f84e.ngrok.io as GRIP origin
...
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Note that it may take a minute or so for the changes to take effect.

Event storage

By default, events aren't persisted anywhere, so if clients get disconnected or if your server fails to publish data to Pushpin or Fanout Cloud, then clients can miss messages. For reliable delivery, you'll want to enable event storage.

First, set up the database tables:

python manage.py migrate

Then, set a storage class in settings.py:

EVENTSTREAM_STORAGE_CLASS = 'django_eventstream.storage.DjangoModelStorage'

That's all you need to do. When storage is enabled, events are written to the database before they are published, and they persist for 24 hours. If clients get disconnected, Pushpin or Fanout Cloud goes down, or your own server goes down or crashes at any time, even mid-publish, the stream will automatically be repaired.

To enable storage selectively by channel, implement a channel manager and override is_channel_reliable.

Receiving in the browser

Include client libraries on the frontend:

<script src="{% static 'django_eventstream/eventsource.min.js' %}"></script>
<script src="{% static 'django_eventstream/reconnecting-eventsource.js' %}"></script>

Listen for data:

var es = new ReconnectingEventSource('/events/?channel=test');

es.addEventListener('message', function (e) {
    console.log(e.data);
}, false);

es.addEventListener('stream-reset', function (e) {
    // ... client fell behind, reinitialize ...
}, false);

Authorization

Declare a channel manager class with your authorization logic:

from django_eventstream.channelmanager import DefaultChannelManager

class MyChannelManager(DefaultChannelManager):
    def can_read_channel(self, user, channel):
        # require auth for prefixed channels
        if channel.startswith('_') and user is None:
            return False
        return True

Configure settings.py to use it:

EVENTSTREAM_CHANNELMANAGER_CLASS = 'myapp.channelmanager.MyChannelManager'

Whenever permissions change, call channel_permission_changed. This will cause clients to be disconnected if they lost permission to the channel.

from django_eventstream import channel_permission_changed

channel_permission_changed(user, '_mychannel')

Selecting channels

By default, the client selects the channels to listen to by providing one or more channel query parameters in the HTTP request. Alternatively, it is possible to use Django view keyword arguments to select the channels. Examples:

# client selects the channels using query parameters:
url(r'^events/', include(django_eventstream.urls))

# client selects a single channel using a path component
url(r'^events/(?P<channel>\w+)/', include(django_eventstream.urls))

# server selects the channels
url(r'^foo/events/', include(django_eventstream.urls), {'channels':['foo']})

# server selects the channels using formatting based on the view keywords
url(r'^objects/(?P<obj_id>\w+)/events/', include(django_eventstream.urls),
    {'format-channels':['object-{obj_id}']})

Note that if view keywords are used, the client cannot use query parameters to select channels.

If even more advanced channel mapping is needed, implement a channel manager and override get_channels_for_request.

django-eventstream's People

Contributors

jkarneges avatar svvitale avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.