The module Flask-SocketIO provides access to low-latency two-way client-server communication for Python Flask apps.
Any of the SocketIO approved client libraries in Python, C++ , Java and Swift, or another compatible framework may be used by the application to build a permanent link to the server.
Related course: Python Flask: Create Web Apps with Flask
Install Flask-SocketIO
Setup your virtual environment
python3 -m venv venv
Source (or activate) the virtual environment
source venv/bin/activate
First install Flask if you haven’t done so:
pip install flask
Install Flask-SocketIO with pip:
pip install flask_socketio --user
Python Flask Websocket
In the example below socket.io and the Flask module are used. socketio is an two-way event-based communication engine.
Events are triggered both by server and connected clients in socketio. If an event is detected, the related call back functions is called.
To implement event triggers or event callbacks in Flask is easy (The example below uses web sockets.)
Create a new file called app.py with this code:
from flask import Flask, render_template |
then create a directory /templates/
with the file index.html. This uses JQuery and socket.io
|
Start your app with:
python app.py
Then open the url localhost:5000, it will output a message is received.
It will pop out some messages like
127.0.0.1 - - [26/Jun/2020 01:36:02] "GET /socket.io/?EIO=3&transport=polling&t=NBjrfLf HTTP/1.1" 200 - |
Btw, you can easily Deploy your Flask app
Related course: Python Flask: Create Web Apps with Flask