✊🏿 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!

Dash with Flask

How can I embed a dash application in a Flask web application? I want to add some design to my application using flask template.

This is my code:

import dash
from dash.dependencies import Output, Input
import dash_core_components as dcc
import dash_html_components as html
import plotly
import random
import plotly.graph_objs as go
from collections import deque
from flask import Flask, render_template

X = deque(maxlen=20)
Y = deque(maxlen=20)
X.append(1)
Y.append(1)

app = dash.Dash(__name__)
app.layout = html.Div(
    [
        dcc.Graph(id='live-update-graph', animate=True),
        dcc.Interval(
            id='interval-component',
            interval=3000,
            n_intervals=0
            )
        ]
    )

@app.callback(Output('live-update-graph', 'figure'),
        [Input('interval-component', 'n_intervals')])
def update_graph(n):
    X.append(X[-1]+1)
    Y.append(Y[-1]+(Y[-1]*random.uniform(-0.1,0.1)))

    data = go.Scatter(
        x = list(X),
        y = list(Y),
        name = 'Scatter',
        mode = 'lines+markers'
        )

    return {'data':[data], 'layout': go.Layout(xaxis = dict(range=[min(X), max(X)]),
                                           yaxis = dict(range=[min(Y), max(Y)]))}

if __name__ == '__main__':
    app.run_server(debug=True)

And this is an example template

<!DOCTYPE html>
<html>
  <head>
    <title>Flask Template Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" 
media="screen">
    <style type="text/css">
      .container {
        max-width: 500px;
        padding-top: 100px;
      }
    </style>
  </head>
  <body>
    <div class="container">

      //Dash grafic
  
    </div>
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
  </body>
</html>

How can I add my dash graph to the template?

Regards.

You can’t integrate Dash apps at the Jinja2 template level, however there are a number of strategies for embedding a Dash app within a Flask app.

See this page of the Dash docs: https://dash.plot.ly/integrating-dash

or how could it be implemented with an iframe?

Hi, you can see my example code for Flask_template_auth_with_Dash :slightly_smiling_face:

1 Like

ey don’t you have tutorial on this. maybe on youtube or udemy.