Dash CallBack 上的自定义装饰器

问题描述 投票:0回答:1

我试图了解是否可以将破折号回调与自定义装饰器一起使用。 基本 Dash 应用程序:

from dash import Dash, html, dcc, callback, Output, Input
import plotly.express as px
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder_unfiltered.csv')

app = Dash(__name__)

app.layout = html.Div([
    html.H1(children='Title of Dash App', style={'textAlign':'center'}),
    dcc.Dropdown(df.country.unique(), 'Canada', id='dropdown-selection'),
    dcc.Graph(id='graph-content')
])

@callback(
    Output('graph-content', 'figure'),
    Input('dropdown-selection', 'value')
)
def update_graph(value):
    dff = df[df.country==value]
    return px.line(dff, x='year', y='pop')

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

我想用作装饰器的功能:

def my_decorator(func):
    def wrapper_function(*args, **kwargs):
        begin = time.time()
        func(*args,  **kwargs)
        end = time.time()
        print("Total time taken in : ", func.__name__, (end - begin))
    return wrapper_function

我尝试执行以下操作:

@my_decorator
@callback(
    Output('graph-content', 'figure'),
    Input('dropdown-selection', 'value')
)
def update_graph(value):
    dff = df[df.country==value]
    return px.line(dff, x='year', y='pop')

这个更新了仪表板,但没有打印总时间

@callback(
    Output('graph-content', 'figure'),
    Input('dropdown-selection', 'value')
)
@my_decorator
def update_graph(value):
    dff = df[df.country==value]
    return px.line(dff, x='year', y='pop')

这个打印时间,但仪表板没有更新。

我需要更新仪表板并打印回调时间。 Python 似乎支持链式装饰器,但@callback 似乎不支持。有办法吗?或者我应该只复制/粘贴到每个函数?

python python-3.x plotly-dash
1个回答
0
投票

问题是您没有在装饰器的内部函数中返回正在装饰的函数的结果 (

wrapper_function
)。在这种情况下,我们需要返回结果,即您的数字。

由于您没有显式返回,

wrapper_function
隐式返回
None
.

如果您查看浏览器的网络选项卡,您可以看到第二次回调尝试的时间是 printend 并且回调也被调用,但是

figure
null
.

您可以将结果存储在一个变量中,并在打印所用时间后返回它:

def my_decorator(func):
    def wrapper_function(*args, **kwargs):
        begin = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print("Total time taken in : ", func.__name__, (end - begin))
        return result
    return wrapper_function

现在这个工作:

@callback(
    Output('graph-content', 'figure'),
    Input('dropdown-selection', 'value')
)
@my_decorator
def update_graph(value):
    dff = df[df.country==value]
    return px.line(dff, x='year', y='pop')
© www.soinside.com 2019 - 2024. All rights reserved.