[BUG] Environment variables from .env file ignored in Dash.run #2902
Description
Describe your context
Please provide us your environment, so we can easily reproduce the issue.
- replace the result of
pip list | grep dash
below
dash 2.17.1
dash-bootstrap-components 1.6.0
dash-core-components 2.0.0
dash-html-components 2.0.0
dash-table 5.0.0
Describe the bug
Environment variables HOST
, PORT
and DASH_PROXY
are ignored if defined in a .env file and loaded using python-dotenv
.
In Dash.run
, environment variables used as default argument values are evaluated at the time the method is defined, not when it is called. This can lead to discrepancies if the environment variables change between definition and execution.
Specifically, this means that environment variables specified in a .env file and loaded using the python-dotenv package will be ignored if they are loaded after the method definition. Since load_dotenv() is typically called after importing Dash, this issue affects many standard usage patterns.
The docs for app.run
say "If a parameter can be set by an environment variable, that is listed too. Values provided here take precedence over environment variables." It doesn't mention that an .env file cannot be used.
Expected behavior
Arguments which can be set using environment variables should reflect variables from the .env file (loaded using python-dotenv
).
Proposed solution
In Dash.app
(dash.py
), set host
, port
and proxy
to None
by default.
def run(
self,
host=None,
port=None,
proxy=None,
...
Then use
host = host or os.getenv("HOST", "127.0.0.1")
port = port or os.getenv("PORT", "8050")
proxy = proxy or os.getenv("DASH_PROXY", None)
at the start of the function itself to read the env vars when the method is called.