如果 Dash 应用程序因导入的大量数据而变慢,如何使它更快 运行

How to make Dash app run faster if its slowed by large data imported

我正在使用 dash 应用程序调用包含 351 列的大约 250,000 个值的大型数据集,以便我可以显示它。然而 运行 需要很长时间,我认为这是因为我从另一个应用程序调用的数据,我用来收集名为 REDCap 的数据。现在我想知道是否有更好的方法可以使我的应用 运行 更快,即使数据来自不同的应用。请参阅下面的代码:

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
from redcap import Project
import pandas as pd

#redcap api and key
api_url = "enter link"
api_key = "enter key"
project = Project(api_url, api_key)

#call data from redcap
def data():
    df = project.export_records(format="df", df_kwargs={"index_col": project.field_names[1]})
    return df

df = data()


#generate table
def generate_table(dataframe, max_rows=10):
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in dataframe.columns])] +

        # Body
        [html.Tr([
            html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
        ]) for i in range(min(len(dataframe), max_rows))]
    )


external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(children=[
    html.H4(children='US Agriculture Exports (2011)'),
    generate_table(df)
])

if __name__ == '__main__':
    app.run_server(debug=True)

请帮助我如何使应用程序 运行 更快,因为我调用数据的部分正在减慢它的速度

这里有几件事:

1) 使用 project.export_records 从 redcap 导出数据可能是不必要的步骤。我不是 100% 确定您正在使用的数据结构,但我建议将对象转换为 pandas 数据框 – Pandas 对于结构化数据非常快。

2) 假设您不打算显示所有数据,我建议将数据框的大小限制为必要的最小大小。

3) 为您的数据帧生成 html 的计算量很大,而且有点循环,依赖于索引。我将对那里的代码进行以下更改:

# Generating the Body (Slightly more readable and a lot less loopy & indexy)
html_all_rows = []
for idx, row in dataframe[:max_rows].iterrows():
   html_row = html.Tr([html.Td(v) for v in row])
   html_all_rows.append(html_row)

4) 或者,我建议使用 Plotly 的内置 datatable。它比典型的 table 更具交互性 + 它允许真正整洁的排序和查询。 datatable 的数据输入是一个 json 类字典,因此访问数据后速度会提高。

5) 同样,我建议只向应用程序加载所需的数据。我无法想象 350 个字段对任何人都有用 – 同样,250,000 行。