Skip to content

Instantly share code, notes, and snippets.

@whalesalad
Last active May 28, 2019 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save whalesalad/11408081 to your computer and use it in GitHub Desktop.
Save whalesalad/11408081 to your computer and use it in GitHub Desktop.
Doing Server-Side Events with Django (hint: it's easy)
import redis
from django.conf import settings
from django.http import StreamingHttpResponse as HttpResponse
def new_connection():
"""
At some point this will evolve into using a connection pool,
but for now it opens a new connection for each user.
"""
return redis.StrictRedis(host=settings.REDIS_HOST,
port=settings.REDIS_PORT,
db=settings.REDIS_WEBSOCKETS_DB)
def message_iterator(identifier):
"""
Subscribes to a team channel on Redis and provides an iterator
to pass published messages back to the client by way of the
StreamingHttpResponse that is returned to the user below.
"""
r = new_connection()
pubsub = r.pubsub()
pubsub.subscribe(identifier)
for message in pubsub.listen():
if message['type'] == 'message':
# This is critical, data that is sent to the browser needs
# to look like "data: <payload>\n\n"
yield "data: %s\n\n" % message['data']
def team_channel(request, identifier=None):
"""
Replacement for a websocket. Provides a Server-Side event endpoint
where clients can connect and recieve updates to a team.
"""
# logic here to validate that the user can access the channel
# if not request.user.can_access_channel(...)
# return 404...
# The content for the response is an iterator, defined above
content = message_iterator(identifier)
# The response (notice import above is StreamingHttpResponse)
# is created by using the iterator and the special content type.
response = HttpResponse(content, content_type="text/event-stream")
# Add an extra header to make sure browsers do not cache the response
response['Cache-Control'] = 'no-cache'
# EASY!
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment