[Chartjs]-Flask Socketio | Update and plot a chart using background tasks created by Flask Executor or ThreadPoolExecutor

2πŸ‘

βœ…

In function(receiving_data) found in the html page , variable plot is used instead of receiving_data. Variable plot is initialized when render_template is evoked. When data is being emitted via sockets, you do not need to pass variable plot when return render_template('views/index_img_soc.html', plot=bar) is called.

See example script below on how to emit data using sockets to the html script.

The script below will automatically update a bar chart without reloading the page.

The code using chart.js instead of plotly. There are much more examples plotting chart.js in javascript as opposed to plotly.

Updated Python script:

import random
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO
from flask_executor import Executor
import pandas as pd
import json
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
thread = None



@socketio.on("response_demo")
def background_task_func():
    """Example of how to send server generated events to clients."""

    socketio.sleep(5)
    print("send")
   
    data = {'Name': ['Tom', 'Joseph', 'Krish', 'John','Shadz'], 'Age': [20, 21, 19, 18,36]} 

    data_2= pd.DataFrame(data)
    
    df_json=data_2.to_json(orient='records')
    result = {"objects": json.loads(df_json)}
    socketio.emit('my_response',result, broadcast=True)

@app.route('/')
def index():
    executor.submit(background_task_func)
    return render_template('index_2.html')



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

Updated html script:

<!DOCTYPE HTML>
<html>
<head>
    <title>Flask-SocketIO Test</title>
    <script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>

</head>

<canvas id="myChart" width="100" height="100"></canvas>
    <script type="text/javascript" charset="utf-8">

// Chart.js Bar Chart
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple"],
        datasets: [{
            data: [2, 2,2, 2,2],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
 
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});


        $(document).ready(function() {

            var socket = io().connect('http://127.0.0.1:5000');
            socket.emit('response_demo')
            socket.on('my_response', function(obj) {
            for (var i=0; i < obj.objects.length; i++) {
             myChart.data.datasets[0].data[i] =obj.objects[i].Age;
             myChart.data.labels[i] =obj.objects[i].Name;
            
            }
            
                myChart.update();
           
            });

        });

</script>
</html>

Leave a comment