Python Friday #199: Adding Dash to an Existing Flask Application

With Dash and Plotly we can create complex interactive dashboards, while Flask works in the background to gives us all the web capabilities. In this post we turn the tables and add Dash to an existing Flask application.

This post is part of my journey to learn Python. You find the code for this post in my PythonFriday repository on GitHub.

 

The pre-existing Flask application

We use this minimalistic Flask application from the Quickstart tutorial:

Since Dash depends on Flask , you should already have the Flask package on your machine. Should this for any reason not be the case, you can install Flask with this command:

 

Add Dash directly to our application

We can add the Dash code from our introduction blog post directly into our minimalistic Flask application. We must make sure that we do not reuse the name app that points to the Flask application for the Dash code and instead use something like dash_app. In the Dash constructor we can specify the path name under which we want to access our Dash dashboard:

If we start this Flask application, we get the “Hello, World!” for the start page. When we go to http://127.0.0.1:5000/dash/, we get our basic Dash page:

Our basic Dash page now runs in our Flask application.

While this approach works for the smallest of applications, it quickly will get a mess.

 

Dash with Blueprint?

Blueprint is usualy the solution to split your Flask application into more manageable parts. Unfortunately, I did not get Flask, Blueprint and Dash to work together. Please leave a comment if you know how to combine these 3 parts.

 

App factory pattern

After a long search I found an approach to separate Flask from Dash using the app factory pattern. For that we wrap a create method around our Dash application and make sure that we set the server parameter in the Dash constructor to False. That way we can set the server later when we have our Flask application.

In our entry file we create the Flask application as usual, expand the Path with the current folder and then import our factory method. When our Flask application is configured, we can pass it to our Dash app with the init_app() method:

If we run our application with python flask_separated.py, we get the “Hello, World!” starting page and our dashboard under the /dash route:

The dashboard looks and works as before.

 

Next

We basically only need to use the parameter routes_pathname_prefix and add our flask application as the server parameter to the Dash constructor to use Dash in an existing Flask application. While this works, I highly recommend using the approach with the factory method to separate Dash into its own part.

Next week we celebrate the milestone of the 200th post for Python Friday and look back at the topics we covered since Python Friday #100.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.