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

flask socketio

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
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app)

@app.route('/')
def index():
return render_template('index.html')

@socketio.on('connect')
def test_connect():
emit('after connect', {'data':'Lets dance'})

if __name__ == '__main__':
socketio.run(app)

then create a directory /templates/ with the file index.html. This uses JQuery and socket.io

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SocketIO example</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>
<script type="text/javascript">
$(document).ready(function() {

// sending a connect request to the server.
var socket = io.connect('http://localhost:5000');

socket.on('after connect', function(msg) {
console.log('After connect', msg);
$('#log').append('<br>' + $('<div/>').text('Received: ' + msg.data).html());
});
});
</script>
</head>
<body>
<h1>SocketIO Example</h1>
<h2>Receive:</h2>
<div id="log"></div>
</body>
</html>

Start your app with:

python app.py

Then open the url localhost:5000, it will output a message is received.

python flask websockets

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 -
127.0.0.1 - - [26/Jun/2020 01:36:07] "GET / HTTP/1.1" 200 -

Related course: Python Flask: Create Web Apps with Flask