【问题标题】:Consistent update dash page across connections跨连接一致更新破折号页面
【发布时间】:2023-02-18 06:32:05
【问题描述】:

我正在制作一个多页面破折号应用程序,我计划使用 Gunicorn 和 Nginx 在服务器上托管它。它将通过网络访问外部服务器上的 PostgreSQL 数据库。

其中一个页面上的数据是通过从数据库中查询获得的,并且应该每 30 秒更新一次。我用来通过dcc.Interval更新@callback

我的代码(简化版):

from dash import Dash, html, dash_table, dcc, Input, Output, callback
import dash_bootstrap_components as dbc
from flask import Flask
import pandas as pd
from random import random

server = Flask(__name__)
app = Dash(__name__, server=server, suppress_callback_exceptions=True, external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = html.Div([
    dcc.Interval(
            id='interval-component-time',
            interval=1000,
            n_intervals=0
        ),
    html.Br(),
    html.H6(id='time_update'),
    dcc.Interval(
            id='interval-component-table',
            interval=1/2*60000,
            n_intervals=0
        ),
    html.Br(),
    html.H6(id='table_update')
    ])

@callback(
    Output('time_update', 'children'),
    Input('interval-component-time', 'n_intervals')
)
def time_update(n_intervals):
    time_show = 30
    text = "Next update in {} sec".format(time_show - (n_intervals % 30))
    return text

@callback(
    Output('table_update', 'children'),
    Input('interval-component-table', 'n_intervals')
)
def data_update(n_intervals):
    # here in a separate file a query is made to the database and a dataframe is returned
    # now here is a simplified receipt df
    col = ["Col1", "Col2", "Col3"]
    data = [[random(), random(), random()]]
    df = pd.DataFrame(data, columns=col)
    return dash_table.DataTable(df.to_dict('records'),
                         style_cell={'text-align': 'center', 'margin-bottom': '0'},
                                style_table={'width':'500px'})

if __name__ == '__main__':
    server.run(port=5000, debug=True)

在本地,一切对我来说都很好,数据库的负载很小,一个这样的请求将 8 个处理器中的 1 个负载 30% 持续 3 秒。

但是,如果你在多个浏览器窗口中打开我的应用程序,那么相同的数据在不同时间两次查询数据库会显示在两个页面上,即负载加倍。我担心当连接超过10个人时,我的数据库服务器将无法承受/会严重冻结,并且其上的数据库应该可以正常工作并且不会崩溃。

问题:

是否可以使不同连接的页面刷新相同?也就是说,这样数据就可以同时针对不同的用户进行更新,并且只需借助对数据库的一次查询。

我研究了文档中有关回调的所有内容,但没有找到答案。

解决方案

感谢您的建议,@Epsi95!我研究了页面 Dash Performance 并将其添加到我的代码中:

cache = Cache(app.server, config={
    'CACHE_TYPE': 'filesystem',
    'CACHE_DIR': 'cache-directory',
    'CACHE_THRESHOLD': 50
})

@cache.memoize(timeout=30)
def query_data():
    # here I make a query to the database and save the result in a dataframe
    return df

def dataframe():
    df = query_data()
    return df

@callback 函数中,我调用了 dataframe() 函数。 一切都按照我需要的方式工作。谢谢你!

【问题讨论】:

  • 我认为你应该使用缓存(或一个简单的文件开始),一个不同的过程,它将在一定的时间间隔内更新缓存。你的破折号应用程序只会读取缓存。
  • @Epsi95 谢谢!将解决方案添加到帖子中

标签: python plotly-dash


【解决方案1】:

出于好奇,为什么你的回调函数必须调用数据框函数?为什么不直接调用 query_data 函数??

【讨论】:

    猜你喜欢
    • 2021-07-16
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2011-08-25
    • 2018-12-01
    • 1970-01-01
    相关资源
    最近更新 更多