Sometimes, we want to implement server push in Python Flask framework.
In this article, we’ll look at how to implement server push in Python Flask framework.
How to implement server push in Python Flask framework?
To implement server push in Python Flask framework, we can send server-sent events.
To do this, we can use the flask-sse package.
We install it by running
pip install flask-sse
Then we use it by writing
from flask import Flask
from flask_sse import sse
app = Flask(__name__)
app.config["REDIS_URL"] = "redis://localhost"
app.register_blueprint(sse, url_prefix='/stream')
@app.route('/send')
def send_message():
sse.publish({"message": "Hello!"}, type='greeting')
return "Message sent!"
to call sse.publish with a dict with the content to send.
The dict will be sent as JSON to the client.
And then in the client, we writer
const source = new EventSource("{{ url_for('sse.stream') }}");
source.addEventListener('greeting', (event) =>{
const data = JSON.parse(event.data);
// ...
}, false);
to create a new EventSource object.
And then we call addEventListener with 'greeting' to listen for greeting type messages.
In the callback, we get the data sent from the server from event.data as a JSON string.
Conclusion
To implement server push in Python Flask framework, we can send server-sent events.
To do this, we can use the flask-sse package.