python - 在重新加载时绘制破折号刷新全局数据

标签 python pandas plotly-dash

想象一下我有一个 dash我希望全局数据在页面重新加载时刷新的应用程序。我正在使用一个函数来提供所描述的布局 here .但是,我确定我应该如何/在哪里定义 df这样我就可以在回调中使用它(就像我想根据一些输入对 df 进行子集化并将其传递给布局表的情况)。我下面的代码在页面刷新时重新加载数据,但回调无法访问 df .
我对 dash 很陌生所以提前为可能愚蠢的问题道歉。

def serve_layout():
    df = # Fetch data from DB
    
    return # Layout

app.layout = serve_layout

@app.callback()
def my_func:
    # Here I want to reference df

最佳答案

在回调之间共享数据的最常见方法是将数据保存在 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 的序列化)可能会导致严重的性能问题。可以通过缓存数据帧服务器端来避免这种情况,或者如 documentation 中所示手动进行。或使用来自 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 的作者.

关于python - 在重新加载时绘制破折号刷新全局数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63225707/

相关文章:

python - Django 如何使用 django.contrib.auth 添加注销成功消息?

python - 从数据框中的所有行附加单词或字符列表

python - 标记数据框的索引

python - 在 App Engine Python 中动态向 Google Datastore 实体添加属性(灵活环境)

python sqlite 'NoneType' 对象不可迭代

python - 如何查看 Dash 应用程序中的活跃用户数?

plotly-dash - 已在 macOS 上安装 Dash,但在运行脚本时出错

python-3.x - 在浏览器网络应用程序中同时对两个视频进行姿势检测不起作用

python - 我想在 python 中创建一个 "CGI script",它驻留在内存中并服务多个请求

python - Pandas groupby 具有滚动日期偏移的多列 - 如何?