如何获取Plotly Dash应用运行所在的URL地址?
获取Plotly Dash应用的运行时URL
本地开发场景
Dash基于Flask构建,你可以直接从启动配置的host和port构建URL,不需要额外抓取。如果是默认配置或自定义了host/port,直接拼接即可:
import dash from dash import html app = dash.Dash(__name__) # 定义启动参数 host = "0.0.0.0" # 或"127.0.0.1" port = 8050 # 构建URL:如果监听所有地址,本地访问用localhost if host in ["0.0.0.0", "::"]: app_url = f"http://localhost:{port}" else: app_url = f"http://{host}:{port}" # 存储到应用变量中,比如app.config app.config["APP_RUNTIME_URL"] = app_url app.layout = html.Div([ html.P(f"当前应用访问地址: {app_url}") ]) if __name__ == "__main__": app.run_server(host=host, port=port, debug=True)
线上部署场景
线上部署时(比如配置了自定义域名),有两种可靠方式:
1. 通过请求上下文获取
在回调或路由中,利用Flask的request对象获取当前请求的域名信息,这种方式能自动适配反向代理或托管平台的配置:
from dash import Input, Output, callback, html, dcc import dash from flask import request app = dash.Dash(__name__) app.layout = html.Div([ dcc.Location(id="url", refresh=False), html.Div(id="url-display") ]) @callback( Output("url-display", "children"), Input("url", "pathname") ) def update_url_display(_): # 获取完整的基础URL(包含协议、域名、端口) full_base_url = request.host_url.rstrip("/") app.config["APP_RUNTIME_URL"] = full_base_url return f"当前应用访问地址: {full_base_url}" if __name__ == "__main__": app.run_server(host="0.0.0.0", port=8050)
2. 通过环境变量配置
很多托管平台(如Heroku、AWS Elastic Beanstalk)会提供环境变量来暴露应用的公网URL,或者你可以手动设置环境变量,代码中直接读取:
import os import dash from dash import html app = dash.Dash(__name__) # 优先读取环境变量,本地开发时用默认值 default_local_url = "http://localhost:8050" app_url = os.getenv("APP_PUBLIC_URL", default_local_url) app.config["APP_RUNTIME_URL"] = app_url app.layout = html.Div([ html.P(f"当前应用访问地址: {app_url}") ]) if __name__ == "__main__": app.run_server(host="0.0.0.0", port=8050)
注意事项
- 本地开发时,如果用
0.0.0.0作为host,意味着监听所有网络接口,本地访问需要用localhost或本机IP,所以代码中做了判断适配。 - 线上部署时,若使用反向代理(如Nginx),需要确保代理传递了正确的
Host头,否则request.host_url可能获取不到正确的域名。
内容的提问来源于stack exchange,提问作者Usman Afridi
相关产品推荐
相关产品推荐

