1 回答

TA貢獻1786條經驗 獲得超11個贊
在回調之間共享數據的最常見方法是將數據保存在一個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 dcc
import dash_html_components as html
import numpy as np
import pandas as pd
from dash_extensions.enrich import Dash, ServersideOutput, Output, Input, Trigger
app = 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 data
if __name__ == '__main__':
app.run_server()
測試過dash-extensions==0.0.27rc1。免責聲明:我是dash-extensions.
添加回答
舉報