下面我有一个基本的破折号应用程序,我在其中查询数据库中的一些数据并将其放入服务器上的商店组件中。我正在摸索如何以设定的时间间隔(服务器端)更新数据存储。在下面的当前配置中,它使用 dcc.Interval 进行更新。当连接多个客户端时,每个人都会触发自己的时间间隔组件,这会很快使数据库死锁。触发在设置的“服务器端”间隔上输出商店的功能的最佳方法是什么?我一直在用this文章作为灵感,但似乎无法完全理解如何适应它。
编辑:我查看了 APScheduler但我不确定如何将它与 dcc.Store 一起使用。这似乎是解决此问题的最佳方式(如果可能的话)。
任何帮助都是极好的!
app.layout = html.Div([
html.Button("Query data", id="btn"),dcc.Graph(id='Time-graph',style={'width': '100%', 'height': '900px'}),
dcc.Store(id="store",storage_type="session"),
dcc.Interval(
id='interval-component-Time',
interval=1 * 8000, # in milliseconds
n_intervals=0
)
])
# Create (server side) cache. Works with any flask caching backend.
cc = CallbackCache(cache=FileSystemCache(cache_dir="../cache"))
@cc.cached_callback(Output("store", "data"), [Trigger("interval-component-Time", "n_intervals")]) # Trigger is like Input, but excluded from args
def query_data():
channel = pyodbc.connect("...connection string...'")
Run=pd.read_sql("command ", channel).iloc[0]['Name']
Event=pd.read_sql("command ", channel).iloc[0]['EventId']
Lap=pd.read_sql("command ", channel)
groups = [Run, Event, Lap]
return groups
@cc.callback(Output("Time-graph", "figure"), [Input("store", "data")])
def update_graph(data):
...code to generate figure...
return fig
cc.register(app)
if __name__ == '__main__':
app.run_server(debug=True)
最佳答案
我建议您将数据库调用放在使用基于时间的缓存装饰的函数中(例如 @cache.memoize(timeout=TIMEOUT)
来自 flask-caching
)。参见 https://dash.plotly.com/performance 上的第二个示例.
这将确保所有用户都访问数据库中的缓存数据,无论用户等待的时间间隔是多少。它只会在缓存的计时器到期后刷新,因此不会在后台无休止地刷新。
关于python - 使用 Plotly Dash 进行服务器端缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69375582/