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
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With