3

As the title suggestions. I have one file main.py with:

import dashApp
from threading import Timer
import webbrowser


if __name__ == "__main__":
    Timer(10, webbrowser.open_new("http://127.0.0.1:8050/")).start()
    dashApp.dashApp()

The second file I have (example from the docs in Dash) is dashApp.py:

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd

def dashApp():
    external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]

    app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

    # assume you have a "long-form" data frame
    # see https://plotly.com/python/px-arguments/ for more options
    df = pd.DataFrame(
        {
            "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
            "Amount": [4, 1, 2, 2, 4, 5],
            "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"],
        }
    )

    fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")

    app.layout = html.Div(
        children=[
            html.H1(children="Hello Dash"),
            html.Div(
                children="""
            Dash: A web application framework for Python.
        """
            ),
            dcc.Graph(id="example-graph", figure=fig),
        ]
    )
    app.run_server(debug=True)

When I run the code though it opens two tabs of the same local host no matter what I try. I thought it was a timing thing, hence the 10 second delay to let Dash start. But it regardless of the delay two tabs open. If I run just the webbrowser code opening to say google.com instead it opens only one.

In the dashApp itself I don't see any calls to open a browser, and infact if I run this code separately it doesn't open a browser at all. The local server just starts are you would expect.

What am I missing?

Fabich
  • 2,768
  • 3
  • 30
  • 44
Chris Macaluso
  • 1,372
  • 2
  • 14
  • 33

1 Answers1

1

I think the problem is that you're running the Dash app in debug mode:

app.run_server(debug=True)

So instead run:

app.run_server()

or set debug to False explicitly.


When you call run_server you run the Flask server associated with your Dash app (source)

The reason it runs twice is because the Werkzeug reloader is active and it spawns a child process to monitor code changes. If you change part of your code when the app is running you will notice that for each saved change another tab opens. For more information see this post.

So

Timer(10, webbrowser.open_new("http://127.0.0.1:8050/")).start()

is actually being run multiple times.


Alternatively you can keep debug=True, but disable the reloader:

app.run_server(debug=True, use_reloader=False)
5eb
  • 14,798
  • 5
  • 21
  • 65