Home »
Python
Implementation of WebSocket using Flask Socket IO in Python
Python WebSocket Implementation: In this tutorial, we are going to learn how to implement WebSocket using Flask Socket IO in Python?
Submitted by Sapna Deraje Radhakrishna, on September 22, 2019
Python WebSocket using Flask Socket IO
Flask is a python web framework built. It is considered more pythonic than Django web framework because in common situations the equivalent Flask Web Application is more explicit. Flask uses restfulness to respond to the HTTP requests. Combining the WebSocket with Flask will make it an implement real-time web application with dual communication with the ease of WebSocket.
Example for simple 'hello world' flask application
Installation of the libraries in the virtual environment,
- Create a virtual environment
-bash-4.2$ python3 -m venv venv
- Source (or activate) the virtual environment
-bash-4.2$ source venv/bin/activate
- Install the required library using pip
(venv) -bash-4.2$ pip install flask
(venv) –basj-4.2$ pip install Flask-SocketIO
Example Server code
from flask import Flask
app = Flask(__name__)
@app.route('/', methods=['GET'])
def hello_world():
return "Hello World"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5005)
Execute the code
(venv) -bash-4.2$ python3 hello_world_flask.py
* Serving Flask app "hello_world_flask" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://0.0.0.0:5005/ (Press CTRL+C to quit)
To test the application, either use the browser and provide the URL as 'http://localhost:5005/' or CURL command
-bash-4.2$ curl http://localhost:5005/
Hello World
-bash-4.2$
Getting Flask working with WebSockets
We will be using socket.io and the associated Flask addon. Socket-IO is a brilliant engine that allows bi-directional event-based communication. For the socket-io communications, 'events' are triggered by either server or connected clients and corresponding call back functions are set to execute when the events are detected.
Implementing the event triggers or binding event callbacks are very simply implemented in Flask using the below code.
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'include_help!'
socketio = SocketIO(app)
@socketio.on('my event', namespace='/my_namespace')
# this method is invoked when an event called
# 'my event' is is triggered
def test_message(message):
# this triggers new event called 'i said'
emit('i said ', {'data': message['data']})
if __name__ == '__main__':
socketio.run(app)
On the client side, a little bit of JavaScript with JQuery is used to handle incoming and outgoing trigger events.
$(document).ready(function() {
// Use a "/my_namespace" namespace.
namespace = '/my_namespace';
// Connect to the Socket.IO server.
// The connection URL has the following format,
// relative to the current page:
// http[s]://<domain>:<port>[/<namespace>]
var socket = io(namespace);
// The callback function is invoked when a connection with the
// server is established.
socket.on('connect', function() {
socket.emit('my_event', {
data: 'I\'m connected!'
});
});
// Event handler for server sent data.
// The callback function is invoked whenever the server emits data
// to the client. The data is then displayed in the "Received"
// section of the page.
socket.on('i said', function(msg) {
$('#log').append('<br>' + $('<div/>').text('Received #' + msg.count + ': ' + msg.data).html());
});
});
And the above effectively, is the skeleton of sending messages between server and client.