Package: django-eventstream
Django EventStreamEventStream provides API endpoints for your Django application that can push data to connected clients. 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/HTTP/1.1Host:api.example.comAccept:text/event-streamThe client would receive a streaming HTTP response with content looking like this:HTTP/1.1200OKTransfer-Encoding:chunkedConnection:Transfer-EncodingContent-Type:text/event-streamevent: message
data: {"foo": "bar"}

event: message
data: {"bar": "baz"}

...Features:Easy to consume from browsers or native applications.Reliable delivery. Events can be persisted to your database, so clients can recover if they get disconnected.Per-user channel permissions.RequirementsDjango 5.0SetupFirst, install this module and the daphne module:pipinstalldjango-eventstreamdaphneAdd thedaphneanddjango_eventstreamapps tosettings.py:INSTALLED_APPS=[..."daphne","django_eventstream",]Add an endpoint inurls.py:fromdjango.urlsimportpath,includeimportdjango_eventstreamurlpatterns=[...path("events/",include(django_eventstream.urls),{"channels":["test"]}),]That's it! If you runpython manage.py runserver, clients will be able to connect to the/events/endpoint and get a stream.To send data to clients, callsend_event:fromdjango_eventstreamimportsend_eventsend_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 usingDjangoJSONEncoder.Note: in a basic setup,send_eventmust be called from within the server process (e.g. called from a view). It won't work if called from a separate process, such as from the shell or a management command.DeployingAfter following the instructions in the previous section, you'll be able to develop and run locally usingrunserver. However, you should not userunserverwhen deploying, and instead launch an ASGI server such as Daphne, e.g.:daphneyour_project.asgi:applicationSeeHow to deploy with ASGI.WSGI mode can work too, but only in combination with a GRIP proxy. SeeMultiple instances and scaling.Multiple instances and scalingIf you need to run multiple instances of your Django app for high availability or scalability, or need to send events from management commands, then you can introduce a GRIP proxy such asPushpinorFastly Fanoutinto your architecture. Otherwise, events originating from an instance will only be delivered to clients connected to that instance.For example, to use Pushpin with your app, you need to do three things:In yoursettings.py, add theGripMiddlewareand setGRIP_URLto reference Pushpin's private control port:MIDDLEWARE=["django_grip.GripMiddleware",...]GRIP_URL='http://localhost:5561'The middleware is part ofdjango-grip, which should have been pulled in automatically as a dependency of this module.Configure Pushpin to route requests to your app, by adding something like this to Pushpin'sroutesfile (usually/etc/pushpin/routes):* localhost:8000 # Replace `localhost:8000` with your app's URL and portConfigure your consuming clients to connect to the Pushpin port (by default this is port 7999). Pushpin will forward requests to your app and handle streaming connections on its behalf.If you would normally use a load balancer in front of your app, it should be configured to forward requests to Pushpin instead of your app. For example, if you are using Nginx you could have configuration similar to:location /api/ {
    proxy_pass http://localhost:7999
}Thelocationblock above will pass all requests coming on/api/to Pushpin.Event storageBy default, events aren't persisted anywhere, so if clients get disconnected or if your server fails to send data, then clients can miss messages. For reliable delivery, you'll want to enable event storage.First, set up the database tables:pythonmanage.pymigrateThen, set a storage class insettings.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, intermediate proxies go 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 overrideis_channel_reliable.Receiving in the browserInclude client libraries on the frontend:<scriptsrc="{% static 'django_eventstream/eventsource.min.js' %}"></script><scriptsrc="{% static 'django_eventstream/reconnecting-eventsource.js' %}"></script>Listen for data:vares=newReconnectingEventSource('/events/');es.addEventListener('message',function(e){console.log(e.data);},false);es.addEventListener('stream-reset',function(e){// ... client fell behind, reinitialize ...},false);AuthorizationDeclare a channel manager class with your authorization logic:fromdjango_eventstream.channelmanagerimportDefaultChannelManagerclassMyChannelManager(DefaultChannelManager):defcan_read_channel(self,user,channel):# require auth for prefixed channelsifchannel.startswith('_')anduserisNone:returnFalsereturnTrueConfiguresettings.pyto use it:EVENTSTREAM_CHANNELMANAGER_CLASS='myapp.channelmanager.MyChannelManager'Whenever permissions change, callchannel_permission_changed. This will cause clients to be disconnected if they lost permission to the channel.fromdjango_eventstreamimportchannel_permission_changedchannel_permission_changed(user,'_mychannel')Note: OAuth may not work with theAuthMiddlewareStackfrom Django Channels. Seethis token middleware.Routes and channel selectionThe channels the client listens to are specified using Django view keyword arguments on the routes. Alternatively, if no keyword arguments are specified, then the client can select the channels on its own by providing one or morechannelquery parameters in the HTTP request.Examples:# specify fixed list of channelspath('foo/events/',include(django_eventstream.urls),{'channels':['foo']})# specify a list of dynamic channels using formatting based on view keywordspath('objects/<obj_id>/events/',include(django_eventstream.urls),{'format-channels':['object-{obj_id}']})# client selects a single channel using a path componentpath('events/<channel>/',include(django_eventstream.urls))# client selects one or more channels using query parameterspath('events/',include(django_eventstream.urls))Note that if view keywords or a channel path component are used, the client cannot use query parameters to select channels.If even more advanced channel mapping is needed, implement a channel manager and overrideget_channels_for_request.Cross-Origin Resource Sharing (CORS) HeadersThere are settings available to set response headersAccess-Control-Allow-Origin,Access-Control-Allow-Credentials, andAccess-Control-Allow-Headers, which areEVENTSTREAM_ALLOW_ORIGINS,EVENTSTREAM_ALLOW_CREDENTIALS, andEVENTSTREAM_ALLOW_HEADERS, respectively.Examples:EVENTSTREAM_ALLOW_ORIGINS=['http://example.com','https://example.com']EVENTSTREAM_ALLOW_CREDENTIALS=TrueEVENTSTREAM_ALLOW_HEADERS='Authorization'Note thatEVENTSTREAM_ALLOW_HEADERSonly takes a single string value and does not process a list.If more advanced CORS capabilities are needed, seedjango-cors-headers.