1

I am using plotly-dash with jupyter dash. I am wondering if I can automatically open a website if Jupyter dash is run and launch the dashboad after app.run_server(mode='external',debug=True,port=8050).

The reason is I have to log in a website to connect to the data for the dashboard.

Thanks

roudan
  • 3,082
  • 5
  • 31
  • 72

1 Answers1

6

Dash runs on Flask in the background, so I found a similar question for Flask which can be adapted for dash similarly (credit to both responders to that question at the time of writing this answer).

Here is an example on how you can adapt it for Dash:

import os
from threading import Timer
import webbrowser

import dash
from dash import html
from dash import dcc

app = dash.Dash(__name__)

app.layout = html.Div(
    [
        dcc.DatePickerRange(id='date-range')
    ]
)

def open_browser():
    if not os.environ.get("WERKZEUG_RUN_MAIN"):
        webbrowser.open_new('http://127.0.0.1:1222/')

if __name__ == "__main__":
    Timer(1, open_browser).start()
    app.run_server(debug=True, port=1222)
Daniel Al Mouiee
  • 1,111
  • 8
  • 11
  • Thasnks Daniel, yes it works. what does this line do? if not os.environ.get("WERKZEUG_RUN_MAIN") – roudan Apr 01 '22 at 13:54
  • 1
    I believe that when the dash server starts up, the underlying flask code set this `WERKZEUG_RUN_MAIN` to `True`, and to prevent the `webbrowser.open_new()` function from being called twice, we check to see if that environment variable has been set, in which case dont run the function. This is the source code for that environment variable https://github.com/pallets/werkzeug/blob/cbd049d88727936173386d2e80bb5ffa51fedd6e/werkzeug/_reloader.py#L129 – Daniel Al Mouiee Apr 01 '22 at 14:01
  • Thanks Daniel, if the website is already opened, how to prevent opening it again? Thanks – roudan Apr 01 '22 at 14:26