python 重定向到破折号中的url

f0brbegy  于 2023-03-16  发布在  Python
关注(0)|答案(2)|浏览(153)

我正在使用破折号来建立一个 Jmeter 板,每当一个特定的数据点被点击时,我会创建一个唯一的网址,我如何将用户重定向到这个创建的网址?我正在使用下面的代码,每当有人点击任何数据点,点击事件将触发和回调函数执行。

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
2hh7jdfx

2hh7jdfx1#

对于clienside callback,使用window.location

app.clientside_callback(
    """
    function(data) {
      console.log(data);
      window.location = 'https://dash.plotly.com/clientside-callbacks';
    }
    """,
    Output('dummy-div', 'children'),
    Input('example-graph', 'clickData'),
    prevent_initial_call=True
)

Nb.此选项还允许在新选项卡中打开目标页面,为此,请将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) # <- prevent redirect on page load !
def redirect_to_url(clickData):
    # do something with clickData
    url = 'https:www.example.com'
    return url

需要注意的几点:

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

rdlzhqv92#

我相信你可以把dcc.Location和这个一起使用,看起来像这样:

@app.callback(Output('dummy-div', 'children'),
              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 None:
       url = 'https:www.example.com'
       # need to develop to a method to redirect to this url
       return dcc.Location(href=url)

https://dash.plotly.com/dash-core-components/location
(if您已经在布局中使用某个位置,您可以将输出更改为该位置)

相关问题