首页 > 解决方案 > 从 dash python 中的 url 获取参数:此 ID 分配给布局中的 dash_core_components.Location 组件,不支持属性

问题描述

以下是我的代码:

我想从 url 中获取参数并在网页中打印出来。

例如, http: //127.0.0.1 :8051/random?xaxis=log&yaxis=log 是我的网址。

我想打印出网页中的路径名,而我现在返回为 None。我哪里错了。

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

app = dash.Dash(__name__)

app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    html.Br(),
    html.Div(id='my-output')])


@app.callback(
    Output(component_id='my-output', component_property='children'),
    Input(component_id='url', component_property='value'))
def update_output_div(value):
    return html.Div([
        html.H1('path is {}'.format(str(value)))
    ])

if __name__ == '__main__':
    app.run_server(debug=True, port= 8051)

我得到的输出为

在此处输入图像描述

标签: pythonplotly-dashdashboard

解决方案


在浏览器中输入网址http://127.0.0.1:8051/random?param1=cat¶m2=dog

猫和狗将被展示

import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
from furl import furl


app = dash.Dash(__name__)


app.config.suppress_callback_exceptions = True
app.layout = html.Div([
    # represents the URL bar, doesn't render anything
    dcc.Location(id='url', refresh=False),

    # content will be rendered in this element
    html.Div(id='content'),
])


@app.callback(Output('content', 'children'),
              [Input('url', 'href')])
def _content(href: str):
    f = furl(href)
    param1= f.args['param1']
    param2= f.args['param2']

    return html.H1(children=param1: {param1} param2: {param2}' )

if __name__ == '__main__':
    app.run_server(debug=True, port= 8051)

推荐阅读