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.
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.
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.
Just do SSE. Omit any other functions such as ID
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'),
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>
@.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.
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