来自另一个文件的Python Dash回调值

2024-04-26 07:26:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: 文件数据pydivapiformatflaskhtml
2条回答

对。您需要interval组件

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

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

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

相关问题 更多 >