Running a Dash app within a Flask app Running a Dash app within a Flask app python python

Running a Dash app within a Flask app


From the docs:

The underlying Flask app is available at app.server.

import dashapp = dash.Dash(__name__)server = app.server

You can also pass your own Flask app instance into Dash:

import flaskserver = flask.Flask(__name__)app = dash.Dash(__name__, server=server)

Now that you have the Flask instance, you can add whatever routes and other functionality you need.

@server.route('/hello')def hello():    return 'Hello, World!'

To the more general question "how can I serve two Flask instances next to each other", assuming you don't end up using one instance as in the above Dash answer, you would use DispatcherMiddleware to mount both applications.

dash_app = Dash(__name__)flask_app = Flask(__name__)application = DispatcherMiddleware(flask_app, {'/dash': dash_app.server})


Set url_base_pathname in your Dash instance.

app_flask = flask.Flask(__name__)app_dash = dash.Dash(__name__, server=app_flask, url_base_pathname='/pathname')

Now you can redirect to your Plotly Dashboard app under any Flask routes you want.

@app_flask.route('/plotly_dashboard') def render_dashboard():    return flask.redirect('/pathname')


Ok for those who are lazy enough like me, here is the code

from dash import Dashfrom werkzeug.wsgi import DispatcherMiddlewareimport flaskfrom werkzeug.serving import run_simpleimport dash_html_components as htmlserver = flask.Flask(__name__)dash_app1 = Dash(__name__, server = server, url_base_pathname='/dashboard' )dash_app2 = Dash(__name__, server = server, url_base_pathname='/reports')dash_app1.layout = html.Div([html.H1('Hi there, I am app1 for dashboards')])dash_app2.layout = html.Div([html.H1('Hi there, I am app2 for reports')])@server.route('/')@server.route('/hello')def hello():    return 'hello world!'@server.route('/dashboard')def render_dashboard():    return flask.redirect('/dash1')@server.route('/reports')def render_reports():    return flask.redirect('/dash2')app = DispatcherMiddleware(server, {    '/dash1': dash_app1.server,    '/dash2': dash_app2.server})run_simple('0.0.0.0', 8080, app, use_reloader=True, use_debugger=True)