python - 重定向到破折号中的 url

标签 python plotly plotly-dash

我正在使用 dash 构建一个仪表板,每当单击特定数据点时,我都会在其中创建一个唯一的 url,如何将用户重定向到此创建的 url? 我使用下面给出的代码,每当有人单击任何数据点时,单击事件就会触发并执行回调函数。

app.layout = html.Div(children=[
    html.H1(children='Plot'),
    dcc.Graph(id='example-graph',
               figure = plot()),
    html.Div(id='dummy-div')
])
@app.callback(Output('dummy-div', 'childern'),
              Input('graph', 'clickData'))
def redirect_to_url(clickData):
    triggered_id = dash.callback_context.triggered[0]['prop_id'].split('.')[0]
    if triggered_id=='graph' and clickData is not None:
       url = 'https:www.example.com'
       # need to develop to a method to redirect to this url

最佳答案

带有clienside callback ,使用window.location :

app.clientside_callback(
    """
    function(clickData) {
      if (clickData?.points?.length) {
        const point = clickData['points'][0];
        const path = point.customdata ?? 'fallbackPath';
        const url = `https://example.com/${path}`;
        window.location = url;
      }
    }
    """,
    Output('dummy-div', 'children'),
    Input('example-graph', 'clickData'),
    prevent_initial_call=True #
)

铌。此选项还允许在新选项卡中打开目标页面,只需将 window.location = url 行替换为:

window.open(url, '_blank');

或者,添加 dcc.Location()布局中的组件,然后您可以使用基本回调更新其 href 属性:

app.layout = html.Div(children=[
    dcc.Location(id='location'),
    html.H1(children='Plot'),
    dcc.Graph(id='example-graph', figure=plot()),
    html.Div(id='dummy-div')
])

@app.callback(Output('location', 'href'),
              Input('example-graph', 'clickData'),
              prevent_initial_call=True)
def redirect_to_url(clickData):
    # do something with clickData
    url = 'https:www.example.com'
    return url

需要注意的一些事项:

  • 如果您只有一个 Input(),则无需检查触发器 id(即条件 iftriggered_id=='graph' 不是必需的)
  • 确保您的输入/输出 ID 与布局中的内容匹配(“graph”与“example-graph”)
  • “每当点击特定数据点时”重定向用户意味着条件 clickData is not None 而不是 clickData is None<

关于python - 重定向到破折号中的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75725718/

相关文章:

python - 使用 Scipy 查找点在凸包上的投影

python - plotly : remove plotted data from graph

python - 如何自动化 Python Dash 应用程序数据拉取?

R绘图显示光标坐标

python - 如果 lat-lon 键不在其他 json 边界内,则删除 json 的功能

python - 更新 Dash 中多个绘图的绘图

python - 如何连接以下两个矩阵?

python - 我的 openssl 和 ssl 默认 CA 证书路径是什么?

python - docker-compose 与 postgres 的 Django 连接

python - 如何将本地镜像(svg/png)添加到绘图布局?