亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Plotly dash 在重新加載時刷新全局數據

Plotly dash 在重新加載時刷新全局數據

守候你守候我 2023-04-25 15:45:40
假設我有一個dash應用程序,我希望全局數據在頁面重新加載時刷新。我正在使用一個函數來提供這里描述的布局。但是,我注意到我應該如何/在哪里定義df這樣我可以在回調中使用它(比如在我想根據df某些輸入對 進行子集化并將其傳遞給布局表的情況下)。我下面的代碼在頁面刷新時重新加載數據,但回調無法訪問df.我很陌生,dash所以提前為潛在的愚蠢問題道歉。def serve_layout():    df = # Fetch data from DB        return # Layoutapp.layout = [email protected]()def my_func:    # Here I want to reference df
查看完整描述

1 回答

?
Qyouu

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.


查看完整回答
反對 回復 2023-04-25
  • 1 回答
  • 0 關注
  • 251 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號