✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚡️ Concerned about the grid? Kyle Baranko teaches how to predicting peak loads using XGBoost. Register for the August webinar!

How to plot a Plotly Graph when using Flask Executor (background task) and Flask Socketio?

I am currently trying to plot a plotly bar chart that is generated in a background task, once the background task is completed, the graph values are emitted using flask socketio to my frontend html and JavaScript code.

Python Script:

from flask import Flask, render_template, request
import pandas as pd
from flask_executor import Executor
import plotly
import plotly.graph_objs as go
from flask_socketio import SocketIO, emit
import json

global test_val
app = Flask(__name__)
socketio = SocketIO(app)
def create_plot(feature_importance):

    data = [
            x=feature_importance['Age'], # assign x as the dataframe column 'x'
            y=feature_importance['Name'], orientation='h'

    graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)

    return graphJSON

def background_task_func():
    global test_val
    global plot
    data = {'Name': ['Tom', 'Joseph', 'Krish', 'John'], 'Age': [20, 21, 19, 18]}  
    test_val= pd.DataFrame(data)
    bar = create_plot(test_val)
    if test_val.shape[0]>1:
        emit('response_output',plot ,broadcast=True)
        #return render_template('views/index_img_soc.html', plot=bar)
@app.route('/', methods=['GET'])
def index():

    return render_template('views/index_img_soc3.html')

if __name__ == "__main__":  
    executor = Executor(app)

Html Code:

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
	#bargraph ={display:none;}

<button id="button_demo" class="w3-button w3-white w3-small w3-border w3-border-green w3-round-large" onclick="myFunctionChart()">View Chart</button>

<div class="chart" id="bargraph">
    <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>
        <script type="text/javascript" charset="utf-8">
            var socket = io().connect('');
            var graphs; 
            socket.on('response_output', function(receiving_data) {   
            graphs = {{receiving_data | safe}};             

	function myFunctionChart() {
	  var x = document.getElementById("bargraph");
	  if (x.style.display === "none") {
		x.style.display = "block";
	  } else {
		x.style.display = "none";

When I run the code, html does not recognize {{receiving_data | safe}}.

and throws an unexpected token “;” error at graphs = {{receiving_data | safe}}; since it reads it as graphs = ; How do I correctly read this variable into the html script? In addition, variable graphs in the html script is undefined.

I am not sure if this example https://newbedev.com/python-save-plotly-plot-to-local-file-and-insert-into-html can be used as a work around, however I was hoping not to save the figure.

I also came across parsing - Json Parse Socket.io to HTML Table - Stack Overflow . How would I use this concept to pass to a plotly graph. Updating {{receiving_data | safe}}; to ${{receiving_data | safe}}; throws Uncaught ReferenceError: $ is not defined.