【问题标题】:send variable from browser to dash plotly dashboard将变量从浏览器发送到 dash plotly 仪表板
【发布时间】:2021-04-23 10:10:54
【问题描述】:

我在代码中使用“值”作为静态变量。当我运行它时,我会得到“http://127.0.0.1:8050/”,在那里我可以看到我的破折号应用程序。我需要“值”作为可以在浏览器中传递的动态变量。 例如。如果我在浏览器中输入http://127.0.0.1:8050/198,它应该会显示 198 而不是 270。

非常感谢您的帮助:)

共享代码和输出结果为图像

import flask
import dash
import dash_html_components as html
import plotly.graph_objects as go
import dash_core_components as dcc

server = flask.Flask(__name__)
app = dash.Dash(__name__, server=server)

fig = go.Figure(go.Indicator(
    mode = "gauge+number",
    value = 270,
    domain = {'x': [0, 1], 'y': [0, 1]},
    title = {'text': "Speed"}))

app.layout = html.Div([
    dcc.Graph(
        id='life-exp-vs-gdp',
        figure=fig
    )
])
@server.route('/test', methods=['POST'])
def req():
    print('Request triggered!')  # For debugging purposes, prints to console
    

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

【问题讨论】:

    标签: flask plotly plotly-dash


    【解决方案1】:

    使用@app.callback 更新图形

    1. 从 dash.dependencies 导入输入、输出

    2. 回调的输入是 url - 路径名,对于 url,您需要在布局中添加 dcc.Location() - 确保 id 与回调输入匹配。回调接收到的路径名将包含“/”。它基本上是您的 host:ip 之后的路径。删除“/”并将路径名转换为int(),然后将此值分配给go.Figure()中的图形“值”

    3. 输出是更新图形后的图形。确保布局中的图形 id 与回调输出 id 匹配。

    您的代码如下所示:

    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    import flask
    import plotly.graph_objects as go
    from dash.dependencies import Input, Output
    
    server = flask.Flask(__name__)
    app = dash.Dash(__name__, server=server)
    
    app.layout = html.Div([
        dcc.Location(id='url', refresh=False),
        dcc.Graph(
            id='life-exp-vs-gdp'
        )
    ])
    
    
    @app.callback(Output('life-exp-vs-gdp', 'figure'), Input('url', 'pathname'))
    def display_page(pathname):
        if pathname == "/":
            pathname = 200
        else:
            pathname = int(pathname.strip('/'))
    
        fig = go.Figure(go.Indicator(
            mode="gauge+number",
            value=pathname,
            domain={'x': [0, 1], 'y': [0, 1]},
            title={'text': "Speed"}))
        return fig
    
    
    if __name__ == '__main__':
        app.run_server(debug=True)
    

    因此,如果您打开:http://127.0.0.1:8050/,这将在仪表中具有一些默认值。如果你打开:http://127.0.0.1:8050/198,这将在仪表中显示 198 个值。

    我希望,这很有用。

    【讨论】:

      猜你喜欢
      • 2020-06-13
      • 1970-01-01
      • 2022-01-21
      • 2020-12-05
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多