【问题标题】:Python Dash - callback value from another filePython Dash - 来自另一个文件的回调值
【发布时间】:2020-10-25 12:56:08
【问题描述】:

我创建了一个基于flask和dash python的仪表板
如何以指定的时间间隔刷新从另一个 .py 文件中提取的数据? 我有一个从 openweathermap API 返回数据的 weather_api.py 文件 我将其称为:

html.Div(children=[
        html.Div(children=[html.Img(src="http://openweathermap.org/img/wn/{}@2x.png".format(WEATHER_API.icon))]),
        html.Div(children=[html.H2("{} ".format(round(WEATHER_API.current_temperature))),
        html.Span(["Data", html.Br()]),
        html.Span("{}".format(WEATHER_API.weather_description))]),
        ])
])

在文件的开头我导入WEATHER_API - 然后它将引用变量,例如: html.Span("{}".format(WEATHER_API.weather_description))

我希望这些数据每次例如刷新一次。 10 分钟 - 现在它的工作原理是数据只是从头开始 - 一旦我运行 Dash,它只会从 API 中“拉”一次数据。是否有可能以某种方式设置 @callback 每 10 分钟从 WEATHER_API 检索数据 - 就像每 10 分钟启动 WEATHER_API.py 一样?

【问题讨论】:

    标签: python flask plotly-dash


    【解决方案1】:

    是的。您需要interval 组件。

    这里有some examples 用于提供实时更新。

    【讨论】:

    • 以这种方式我已经更新了我的图表 - 问题是我不知道如何只更新数据 - 到weather_api.py 我添加了一个返回当前时间和应用程序布局外观的变量像 html.Div(id="number-output"), dcc.Interval(id='interval-component',interval=3000 和回调像:@app.callback(Output('number-output', 'children'), [Input('interval-component', 'n_intervals')]) def update_output(n): return html.Span('Longitude: {}'.format(WEATHER_API.time)), - 显示时间,但 WEATHER_API.time 不会每秒更新一次
    【解决方案2】:

    我找到了一个解决方案 - 您可以轻松地从另一个脚本返回一个函数值 - 您只需要一个正确的引用:

    import script.py
    
    app.layout = html.Div(
        [
    
            html.Div(id="number-output"),
            dcc.Interval(id='interval-component',
    interval=1000,  # in millisecondsn_intervals=0
            ),
        ]
    )
    
    
    @app.callback(Output('number-output', 'children'),
                  [Input('interval-component', 'n_intervals')])
    
    def update_output(n):
        return html.Span('Output: {}'.format(script.test()))
    

    一个有用的例子: https://dash.plotly.com/live-updates

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-04
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      相关资源
      最近更新 更多