An example of how to use a websocket server to update a web-based visualization in a Python loop.
This repository illustrates how to start and update a web-based visualization tool in real-time from a single Python script in an asynchronous manner, without having to refress the web-browser page.
This file represents the core of the program and contains:
- A class
WsServer
that represents a Python WebSocket server. - A class
HTTPServer
used to start an HTTP server. - A function
start()
to start the web-based visualization. - A function
update()
to update the web-based visualization. - A function
close()
to end the visualization. - A script that can be used as example.
This file contains a very simple ~10-line HTML code that renders the progress bar to be updated by the Python loop.
This file contains the JavaScript code used to communicate with the WebSocket Server and update the status of the progress bar.
The example Python script works as follows.
- Initialize the HTTP and WebSocket servers in two separate threads.
- Start a loop. At every iteration, do: 1. Send an update message through WebSocket (no need to wait, everything is asynchronous).
- The message is received by the Javascript WebSocket connection and the status of the progress bar is updated accordingly.
You can clone this repository with:
git clone https://github.com/robinhenry/python-websocket-visualization
There are very few changes that need to be made to use this framework for any web-based visualization:
- Edit the index.html file to your liking. Make sure to give an
id
property to all elements that you will want to dynamically update. - Edit the
ws.onmessage
JavaScript function to update any HTML elements or interest upon recept of a new message. - Edit the
update()
Python function to add to the WebSocket message any information required by 2. - That's it!
I hope you will find it useful!