Thanks! We'll be in touch in the next 12 hours
Oops! Something went wrong while submitting the form.

How to Implement Server Sent Events Using Python Flask and React

Sagar Khangan

Full-stack Development

A typical Request Response cycle works such that client sends request to server and server responds to that request. But there are few use cases where we might need to send data from server without request or client is expecting a data that can arrive at anonymous time. There are few mechanisms available to solve this problem.

Server Sent Events

Broadly we can classify these as client pull and server push mechanisms. Websockets is a bi directional mechanism where data is transmitted via full duplex TCP protocol. Client Pull can be done using various mechanisms like -

  1. Manual refresh - where client is refreshed manually
  2. Long polling where a client sends request to server and waits until response is received, as soon as it gets response, a new request is sent.
  3. Short Polling is when a client continuously sends request to server in a definite short intervals.

Server sent events are a type of Server Push mechanism, where client subscribes to a stream of updates generated by a server and, whenever a new event occurs, a notification is sent to the client.

Why ServerSide events are better than polling:

  • Scaling and orchestration of backend in real time needs to be managed as users grow.
  • When mobile devices rapidly switch between WiFi and cellular networks or lose connections, and the IP address changes, long polling needs to re-establish connections.
  • With long polling, we need to manage the message queue and catch up missed message.
  • Long polling needs to provide load balancing or fail-over support across multiple servers.

SSE vs Websockets

SSEs cannot provide bidirectional client-server communication as opposed to WebSockets. Use cases that require such communication are real-time multiplayer games and messaging and chat apps. When there's no need for sending data from a client, SSEs might be a better option than WebSockets. Examples of such use cases are status updates, news feeds and other automated data push mechanisms. And backend implementation could be easy with SSE than with Websockets. Also number of open connections is limited for browser for SSE.

Also, learn about WS vs SSE here.

Implementation

The server side code for this can be implemented in any of the high level language. Here is a sample code for Python Flask SSE. Flask SSE requires a broker such as Redis to store the message. Here we are also using Flask APScheduler, to schedule background processes with flask .

Here we need to install and import ‘flask_sse’ and ‘apscheduler.’

CODE: https://gist.github.com/velotiotech/c21cdd7fd2ebaf4b098f071838d48789.js

Now we need to initialize flask app and provide config for Redis and a route or an URL where the client would be listening to this event.

CODE: https://gist.github.com/velotiotech/f7e602669ebe534871002f278154877e.js

To publish data to a stream we need to call publish method from SSE and provide a type of stream.

CODE: https://gist.github.com/velotiotech/179e20e84f49981f96bf218073822c75.js

In client, we need to add an event listener which would listen to our stream and read messages.

CODE: https://gist.github.com/velotiotech/223270b855e3c6409f8a9953c7eec61b.js

Check out a sample Flask-React-Redis based application demo for server side events.

Here are some screenshots of client -

 First Server Sent Event
Fig: First Event

 Second Server Sent Event
 Fig: Second Event

Server logs:

CODE: https://gist.github.com/velotiotech/df7ad8e76e3f68f120521de53f2d10d4.js

Use Cases of Server Sent Events

Let’s see the use case with an example - Consider we have a real time graph showing on our web app, one of the possible options is polling where continuously client will poll the server to get new data. Other option would be to use server sent events, which are asynchronous, here the server will send data when updates happen.

Other applications could be

  • Real time stock price analysis system
  • Real time social media feeds
  • Resource monitoring for health, uptime

Conclusion

In this blog, we have covered how we can implement server sent events using Python Flask and React and also how we can use background schedulers with that. This can be used to implement a data delivery from the server to the client using server push.

Get the latest engineering blogs delivered straight to your inbox.
No spam. Only expert insights.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Did you like the blog? If yes, we're sure you'll also like to work with the people who write them - our best-in-class engineering team.

We're looking for talented developers who are passionate about new emerging technologies. If that's you, get in touch with us.

Explore current openings

How to Implement Server Sent Events Using Python Flask and React

A typical Request Response cycle works such that client sends request to server and server responds to that request. But there are few use cases where we might need to send data from server without request or client is expecting a data that can arrive at anonymous time. There are few mechanisms available to solve this problem.

Server Sent Events

Broadly we can classify these as client pull and server push mechanisms. Websockets is a bi directional mechanism where data is transmitted via full duplex TCP protocol. Client Pull can be done using various mechanisms like -

  1. Manual refresh - where client is refreshed manually
  2. Long polling where a client sends request to server and waits until response is received, as soon as it gets response, a new request is sent.
  3. Short Polling is when a client continuously sends request to server in a definite short intervals.

Server sent events are a type of Server Push mechanism, where client subscribes to a stream of updates generated by a server and, whenever a new event occurs, a notification is sent to the client.

Why ServerSide events are better than polling:

  • Scaling and orchestration of backend in real time needs to be managed as users grow.
  • When mobile devices rapidly switch between WiFi and cellular networks or lose connections, and the IP address changes, long polling needs to re-establish connections.
  • With long polling, we need to manage the message queue and catch up missed message.
  • Long polling needs to provide load balancing or fail-over support across multiple servers.

SSE vs Websockets

SSEs cannot provide bidirectional client-server communication as opposed to WebSockets. Use cases that require such communication are real-time multiplayer games and messaging and chat apps. When there's no need for sending data from a client, SSEs might be a better option than WebSockets. Examples of such use cases are status updates, news feeds and other automated data push mechanisms. And backend implementation could be easy with SSE than with Websockets. Also number of open connections is limited for browser for SSE.

Also, learn about WS vs SSE here.

Implementation

The server side code for this can be implemented in any of the high level language. Here is a sample code for Python Flask SSE. Flask SSE requires a broker such as Redis to store the message. Here we are also using Flask APScheduler, to schedule background processes with flask .

Here we need to install and import ‘flask_sse’ and ‘apscheduler.’

CODE: https://gist.github.com/velotiotech/c21cdd7fd2ebaf4b098f071838d48789.js

Now we need to initialize flask app and provide config for Redis and a route or an URL where the client would be listening to this event.

CODE: https://gist.github.com/velotiotech/f7e602669ebe534871002f278154877e.js

To publish data to a stream we need to call publish method from SSE and provide a type of stream.

CODE: https://gist.github.com/velotiotech/179e20e84f49981f96bf218073822c75.js

In client, we need to add an event listener which would listen to our stream and read messages.

CODE: https://gist.github.com/velotiotech/223270b855e3c6409f8a9953c7eec61b.js

Check out a sample Flask-React-Redis based application demo for server side events.

Here are some screenshots of client -

 First Server Sent Event
Fig: First Event

 Second Server Sent Event
 Fig: Second Event

Server logs:

CODE: https://gist.github.com/velotiotech/df7ad8e76e3f68f120521de53f2d10d4.js

Use Cases of Server Sent Events

Let’s see the use case with an example - Consider we have a real time graph showing on our web app, one of the possible options is polling where continuously client will poll the server to get new data. Other option would be to use server sent events, which are asynchronous, here the server will send data when updates happen.

Other applications could be

  • Real time stock price analysis system
  • Real time social media feeds
  • Resource monitoring for health, uptime

Conclusion

In this blog, we have covered how we can implement server sent events using Python Flask and React and also how we can use background schedulers with that. This can be used to implement a data delivery from the server to the client using server push.

Did you like the blog? If yes, we're sure you'll also like to work with the people who write them - our best-in-class engineering team.

We're looking for talented developers who are passionate about new emerging technologies. If that's you, get in touch with us.

Explore current openings