Snobby Snobby - 1 month ago 19
Python Question

Push data from backend (python) to JS

Front-end part

I have an AJAX request which is trying to GET data from my back-end handle every second.

If there is any data, I get this data, add it to my HTML page (without reloading), and continue pulling data every second waiting for further changes.

Back-end part

I parse web-pages every minute with Celery.

Extract data from them and pass it to an array (that is a trigger for AJAX request that there is new data).


It seems to me that there is another solution for this issue.

I don't want to ask for data from JS to back-end. I want to pass data from back-end to JS, when there are any changes. But without page reload.

How can I do this?


Yes, there is. You can use Websockets or SSE(server-side-event). Basically it depends on your specific needs but consider:

websocket - two way data flow. Client can send data to server and vise versa.

The WebSocket Protocol enables two-way communication between a client running untrusted code in a controlled environment to a remote host
that has opted-in to communications from that code. Check python-websockets-example on Git for examples.

SSE - one way data flow(Server -> Client)

To enable servers to push data to Web pages over HTTP or using dedicated server-push protocols, this specification introduces the EventSource interface.

Using this API consists of creating an EventSource object and registering an event listener.

SSE Flask example.