user350540
user350540

Reputation: 469

Embed Plotly Dash into Flask Application

I have successfully created my first Flask application and divided my code into a series of blueprints as my code base will grow substantially over time. I am now trying to embed a plotly dashboard (or maybe just a plotly visual display) into my app.

For now, I'm using a toy example I took from the web to learn plotly. The second code chunk launches the dash, but my goal is to integrate that second code into my main flask app. Provisionally, I'd like for it to be a route in the main app (I'll parse it out into a blueprint module later), but cannot find from the plotly documentation a didactic example showing how to integrate these together.

Am looking for some code support who might be able to show how the second can be seamlessly integrated into the main application as a route.

This link gave me some ideas to try, Running a Dash app within a Flask app, but I am not quite successful with some of the ideas proposed there.

from flask import Flask, render_template, request, session
from flask_session import Session

app = Flask(__name__)
app.secret_key = 'abcdefg'

### Import and Register Blueprints 
from Help.routes import help
from Datatools.routes import data_tools
from Configtools.routes import config_tools
from wordAnalyzer.routes import word_analyzer
from ScoringTools.routes import test_scoring

app.register_blueprint(help)
app.register_blueprint(data_tools)
app.register_blueprint(config_tools)
app.register_blueprint(word_analyzer)
app.register_blueprint(test_scoring)

@app.route('/')
def homepage():
    return render_template('index.html')   

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

The plotly app

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd

df = pd.read_excel("https://github.com/chris1610/pbpython/blob/master/data/salesfunnel.xlsx?raw=True")
pv = pd.pivot_table(df, index=['Name'], columns=["Status"], values=['Quantity'], aggfunc=sum, fill_value=0)

trace1 = go.Bar(x=pv.index, y=pv[('Quantity', 'declined')], name='Declined')
trace2 = go.Bar(x=pv.index, y=pv[('Quantity', 'pending')], name='Pending')
trace3 = go.Bar(x=pv.index, y=pv[('Quantity', 'presented')], name='Presented')
trace4 = go.Bar(x=pv.index, y=pv[('Quantity', 'won')], name='Won')

app = dash.Dash()

app.layout = html.Div(children=[
    html.H1(children='Sales Funnel Report'),
    html.Div(children='''National Sales Funnel Report.'''),
    dcc.Graph(
        id='example-graph',
        figure={
            'data': [trace1, trace2, trace3, trace4],
            'layout':
            go.Layout(title='Order Status by Customer', barmode='stack')
        })
])

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

UPDATE

I'm wondering if it's possible to do something along the lines of the following, such that the visual display is produced and outputted to an html file I create. My thinking here is that my app now is set up to allow a custom file input and then the user could read in a data file and it would be passed to the graphic.

@server.route('/fake')
def fake():
    df = pd.read_excel("https://github.com/chris1610/pbpython/blob/master/data/salesfunnel.xlsx?raw=True")
    pv = pd.pivot_table(df, index=['Name'], columns=["Status"], values=['Quantity'], aggfunc=sum, fill_value=0)
    trace1 = go.Bar(x=pv.index, y=pv[('Quantity', 'declined')], name='Declined')
    trace2 = go.Bar(x=pv.index, y=pv[('Quantity', 'pending')], name='Pending')
    trace3 = go.Bar(x=pv.index, y=pv[('Quantity', 'presented')], name='Presented')
    trace4 = go.Bar(x=pv.index, y=pv[('Quantity', 'won')], name='Won')
    app = dash.Dash()
    app.layout = html.Div(children=[
        html.H1(children='Sales Funnel Report'),
        html.Div(children='''National Sales Funnel Report.'''),
        dcc.Graph(
            id='example-graph',
            figure={
                'data': [trace1, trace2, trace3, trace4],
                'layout':
                go.Layout(title='Order Status by Customer', barmode='stack')
            })
    ])
    return  render_template('fake.html', dashboard = dcc.Graph) 

Upvotes: 0

Views: 6289

Answers (1)

emher
emher

Reputation: 6014

To avoid confusion of the Flask and Dash objects, let's rename the Flask object to server (they are both called app in your code), i.e.

...
server = Flask(__name__)
...

Now, to integrate the Dash application with the Flask server, you simply pass the server as a keyword,

...
app = dash.Dash(server=server, url_base_pathname="/app_base_path/")
...

The url_base_pathname argument is optional, it simply allows you to control at which path the Dash app is registered.

Upvotes: 3

Related Questions