【问题标题】:Plotly dash user dependent server side cachingPlotly dash 用户依赖的服务器端缓存
【发布时间】:2020-08-05 13:58:28
【问题描述】:

我在我的dash 应用程序中使用服务器端缓存,并且我遵循了documentation 中的示例4。我用它来查询和处理“全局”数据,然后在应用程序的不同组件之间共享这个准备好的数据集。

我正在尝试调整示例,使缓存也依赖并重新加载某些用户输入。

我尝试过类似下面的方法,但实际上没有意义 - 实现我所追求的最佳方法是什么?

app = dash.Dash(__name__)

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

def get_dataframe(session_id, user_input_value):
    @cache.memoize()
    def query_and_serialize_data(session_id):
        df = # Here I make my query based on user_input_value 
             # If there is no input I just return an empty df
        return df.to_json()
    return pd.read_json(query_and_serialize_data(session_id))

def serve_layout():
    session_id = str(uuid.uuid4())

    return html.Div([
        html.Div(session_id, id='session-id', style={'display': 'none'}),
        # User input            
        # My output which doesn't behave as expected
    ])

app.layout = serve_layout

# Callback related to the user input

@app.callback(
    [
        Output('my-output', 'output-component')
    ],
    [
        Input('session-id', 'children'),
        Input('user-input', 'value')
    ]
)
def generate_output(session_id, user_input_value):
    df = get_dataframe(session_id, user_input_value)
    return # Output component

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

【问题讨论】:

    标签: python pandas plotly plotly-dash


    【解决方案1】:

    在您发布的代码中,user_input_value 值永远不会到达记忆函数。如果您更改代码以使其正常运行,即将user_input_value 传递给query_and_serialize_data 函数,它应该按预期工作

    def get_dataframe(session_id, user_input_value):
        @cache.memoize()
        def query_and_serialize_data(session_id, user_input_value):
            df = # Here I make my query based on user_input_value 
                 # If there is no input I just return an empty df
            return df.to_json()
        return pd.read_json(query_and_serialize_data(session_id, user_input_value))
    

    【讨论】:

    • 谢谢!那应该这样做。尽管如此,我现在还了解到 dash-extensions ServersideOutput 可能是一个更清洁的解决方案。我上面的方法需要使用“全局”数据将用户输入传递给每个回调。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 2021-01-04
    • 1970-01-01
    相关资源
    最近更新 更多