How to do Server-Sent Events in Django

I don't have enough time to do WebSocket with Django, but I wanted to do server-side push, so I decided to use SSR with Gori push. I would appreciate it if you could point out any corrections.

Caution

In my experiments on the local server, when I interrupted the connection, [ConnectionAbortedError: [WinError 10053] the established connection was aborted by the host computer software. I get the error message It's probably harmless, but it's unpleasant, so be careful when handling it.

What is Server-Sent Events in the first place?

Roughly speaking, it's a great Comet. In other words, it's like a server-side push. WebSocket may be better, but the advantage is lower implementation cost If you want to know more, please check.

Code content overview

Just do SSE. Omit any other functions such as ID

code

Python side

Streaming

views.py


from django.views.decorators.http import condition
from django.http import StreamingHttpResponse
from django.views.generic import UpdateView, DetailView, FormView, TemplateView, DeleteView
import time


@condition(etag_func=None)
def stream_response(request):
    resp = StreamingHttpResponse(stream_response_generator(), content_type='text/event-stream')
    return resp


def stream_response_generator():
    while(True):
        yield "data: %s\n" \
              "retry:1000\n\n" % 0
        time.sleep(1)


class DevSSETemplate(TemplateView):
    template_name = "stream.html"

urls.py


    url(r'^stream/$', views.stream_response, name='stream_response'),
    url(r'^stream/template/$', DevSSETemplate.as_view(), name='stream_response_template'),

JavaScript side

Just get it and add it to the list

stream.html


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id ="log"></div>
</body>
<script>

window.onload = function() {
  var evtSource = new EventSource("{% url 'accounts:stream_response' %}");
  var eventList = document.getElementById("log");

  evtSource.onmessage = function(e) {
      console.log(e);
      var newElement = document.createElement("li");

      newElement.innerHTML = "message: " + e.data;
      eventList.appendChild(newElement);
  };
}

</script>
</html>

Commentary

@.condition(etag_func=None) Disable ETag (around the cache)? StreamingHttpResponse Streaming can be done using this method. It seems that it is usually used when sending PDF etc. Including this, Django has a lot of features, and it's nice to have access to the itch.

Impressions

It worked for the time being SSE has a low implementation cost and seems to be useful in frameworks where WebSocket support is not advanced, but it is strange that it is not popular for some reason ~~ probably because it is not good ~~

Recommended Posts

How to do Server-Sent Events in Django
[Python] How to do PCA in Python
How to reflect CSS in Django
How to do arithmetic with Django template
How to do R chartr () in Python
How to delete expired sessions in Django
How to convert DateTimeField format in Django
How to implement Rails helper-like functionality in Django
How to reflect ImageField in Django + Docker (pillow)
How to run some script regularly in Django
How to create a Rest Api in Django
How to get multiple model objects randomly in Django
How to do hash calculation with salt in Python
How to do zero-padding in one line with OpenCV
How to use bootstrap in Django generic class view
How to upload files in Django generic class view
How to use Decorator in Django and how to make it
How to reference static files in a Django project
[Django 2.2] How do you display relation destinations in Django? [List View]
How to check ORM behavior in one file with django
How to update user information when logging in to Django RemoteUserMiddleware
[Django] How to give input values in advance with ModelForm
How to generate a query using the IN operator in Django
How to do the initial setup from Django project creation
[Blender] How to handle mouse and keyboard events in Blender scripts
In Django, how to abbreviate the long displayed string as ....
How to handle session in SQLAlchemy
[Django] How to test Form [TDD]
How to use classes in Theano
How to write soberly in pandas
How to collect images in Python
Errors related to memcached in django
How to update Spyder in Anaconda
How to use SQLite in Python
How to convert 0.5 to 1056964608 in one shot
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to use PubChem in Python
How to write Django1.9 environment-independent wsgi.py
How to run TensorFlow 1.0 code in 2.0
How to handle Japanese in Python
How to log in to Docker + NGINX
How to authenticate with Django Part 2
How to authenticate with Django Part 3
How to call PyTorch in Julia
[Django] How to read variables / constants defined in an external file
How to deploy a Django app on heroku in just 5 minutes
[Tips] How to do template extends when creating HTML with django
How to use calculated columns in CASTable
[Introduction to Python] How to use class in Python?
How to suppress display error in matplotlib
How to access environment variables in Python
How to dynamically define variables in Python
How to check the version of Django
How to convert csv to tsv in CLI
[Itertools.permutations] How to put permutations in Python
How to implement nested serializer in drf-flex-fields
How to work with BigQuery in Python
How to execute commands in jupyter notebook
How to do'git fetch --tags' in GitPython