Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make SSE with Python (Django)?

I have two different pages, one (A) that displays data taken from a model object, and one (B) that changes its fields. I would like that when the post data is sent from B to the server, the server changes the values in A. What is the best way to do it?

This example could work for me but it's in PHP... there is a way to replicate it whit Python? https://www.w3schools.com/html/html5_serversentevents.asp

like image 591
Lorenzo Fiamingo Avatar asked Jan 23 '19 11:01

Lorenzo Fiamingo


People also ask

Does django support sse?

EventStream 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.

What is Python SSE?

Server-sent events (SSE) is a way to send data to the browser without reloading the page. This allows you to use streaming data and build real-time applications that can be used in a variety of scenarios. FastAPI is a Python framework that makes it easy to build APIs.

Is Django pure Python?

Written in pure Python, Django has a clean pythonic structure. It started as a Model–View–Controller (MVC) framework, and this concept still exists in the current version.

What are server side events?

Server-Sent Events (SSE) is a server push technology enabling a client to receive automatic updates from a server via an HTTP connection, and describes how servers can initiate data transmission towards clients once an initial client connection has been established.


2 Answers

After reading this, I think I understood the whole thing (please comment if I’m wrong).



Django does NOT natively support keep-alive connections. 
This means, when the client gets the message from the server, the connection is immediately closed after (like any classic HTTP request/response cycle).


What’s different with text/event-stream request, is that the client automatically tries to reconnect to the server every second (the length can be changed with a retry parameter).



Unfortunately, it seems using SSE in that case has no interest since it has the same con’s that polling (ie. a request/response cycle occurs each X seconds).



As expected and mentioned in other answers, I would need django-channels to create a persistent connection that prevent HTTP request/response overheads and ensure the message is sent immediately.


like image 140
David D. Avatar answered Sep 23 '22 08:09

David D.


As mentioned in other answers, you will need to use Django Channels to properly handle asynchronous communication without tying up threads.

For an example, see the django-eventstream library which uses Channels to implement SSE.

like image 43
jkarneges Avatar answered Sep 21 '22 08:09

jkarneges