Hmm, there used to be a good section on this in the Dash docs which seems to have been removed for some reason
Anyway, here’s some options
Flask
Integration with Flask is easier because Dash is built on top of Flask. There are two main options here:
- Host the Dash app on a particular route of the existing Flask app. This is done by passing the Flask app to your Dash app with the
server
keyword argument. - Stitch together multiple Flask apps and Dash apps using Werkzeug’s
DispatcherMiddleware
.
Host on a route of existing Flask app
Here’s a simple example. Note you need to set routes_pathname_prefix
on the Dash app, which controls where the Dash app will be visible.
import dash
import dash_html_components as html
import flask
server = flask.Flask(__name__)
@server.route("/")
def home():
return "Hello, Flask!"
app = dash.Dash(server=server, routes_pathname_prefix="/dash/")
app.layout = html.Div("This is the Dash app.")
if __name__ == "__main__":
app.run_server(debug=True)
You can access the Flask home page at localhost:8050/
and the Dash app at localhost:8050/dash/
.
DispatcherMiddleware
You can access the underlying Flask server of any Dash app you create using .server
which means you can stitch together the apps using DispatcherMiddleware
from Werkzeug. Here’s a simple example. Note this time we set requests_pathname_prefix
rather than routes_pathname_prefix
.
import dash
import dash_html_components as html
import flask
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.serving import run_simple
server = flask.Flask(__name__)
@server.route("/")
def home():
return "Hello, Flask!"
app1 = dash.Dash(requests_pathname_prefix="/app1/")
app1.layout = html.Div("Hello, Dash app 1!")
app2 = dash.Dash(requests_pathname_prefix="/app2/")
app2.layout = html.Div("Hello, Dash app 2!")
application = DispatcherMiddleware(
server,
{"/app1": app1.server, "/app2": app2.server},
)
if __name__ == "__main__":
run_simple("localhost", 8050, application)
You can see the Flask home page at localhost:8050/
and the two Dash apps at localhost:8050/app1/
and localhost:8050/app2/
. Note that run_simple
is definitely only suitable for development and you should use something like gunicorn
to actually serve your app when it’s ready.
This approach is used in the dash-bootstrap-components documentation if you’re interested.
Django
For integration with Django you should check out django-plotly-dash. I don’t know so much about this, but if you’re a Django user I think it’s the best option.