Qyouu
在回调之间共享数据的最常见方法是将数据保存在一个dash_core_components.Store对象中,def serve_layout(): df = # Fetch data from DB store = Store(id="mystore", data=df.to_json()) # The store must be added to the layout return # Layout 然后,您可以将商店添加为State需要访问数据的回调的参数,@app.callback(..., [State("mystore", "data")])def my_func(..., data): df = pd.read_json(data)这种方法的主要缺点是每次调用回调时都会在客户端和服务器之间交换数据。如果数据框很小,这并不重要,但如果它很大,数据交换(以及到/从 JSON 的序列化)可能会导致严重的性能问题。可以通过缓存数据框服务器端来避免这种情况,可以手动如文档中所示,也可以使用dash-extensions. 这是后者的一个小例子,import dash_core_components as dccimport dash_html_components as htmlimport numpy as npimport pandas as pdfrom dash_extensions.enrich import Dash, ServersideOutput, Output, Input, Triggerapp = Dash()app.layout = html.Div([dcc.Store(id="store"), # this is the store that holds the data html.Div(id="onload"), # this div is used to trigger the query_df function on page load html.Div(id="log")])@app.callback(ServersideOutput("store", "data"), Trigger("onload", "children"))def query_df(): return pd.DataFrame(data=np.random.rand(int(10)), columns=["rnd"]) # some random example data@app.callback(Output("log", "children"), Input("store", "data"))def print_df(df): return df.to_json() # do something with the dataif __name__ == '__main__': app.run_server()测试过dash-extensions==0.0.27rc1。免责声明:我是dash-extensions.