本文共 2106 字,大约阅读时间需要 7 分钟。
在Dash框架中,通过dash.dependencies.Output和dash.dependencies.Input定义输入输出关系,并结合回调函数处理数据,是实现数据交互的核心方法。为了提高开发效率,可以将通用的处理逻辑封装到独立函数中,方便在多个回调中重复使用。
以下是一个简洁的示例:
import dashfrom dash import html, dccimport dash_bootstrap_components as dbcfrom dash.dependencies import Input, Outputdef process_input(value): return f"Processed: {value}"app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])app.layout = dbc.Container([ dbc.Row([ dbc.Col(dcc.Input(id="input-text", type="text"), width=6), dbc.Col(html.Div(id="output-text"), width=6) ])], fluid=True)@app.callback( Output("output-text", "children"), [Input("input-text", "value")])def update_output(input_value): return process_input(input_value) 这个例子定义了一个处理输入的函数process_input,将其应用于输入数据并返回结果。update_output回调函数接收输入值,通过调用封装的处理函数生成输出。
如果需要多个输出使用相同的逻辑,可以按照以下方式实现:
@app.callback( [Output("output-text1", "children"), Output("output-text2", "children")], [Input("input-text", "value")])def update_outputs(input_value): processed_value = process_input(input_value) return processed_value, processed_value 在测试场景中,可以使用pytest和dash.testing来验证回调逻辑。例如:
import dashfrom dash import html, dccimport dash_bootstrap_components as dbcfrom dash.dependencies import Input, Outputimport pytestfrom dash.testing.wait import untildef test_callback(): app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) app.layout = dbc.Container([ dbc.Row([ dbc.Col(dcc.Input(id="input-text", type="text"), width=6), dbc.Col(html.Div(id="output-text"), width=6) ]) ], fluid=True)@app.callback( Output("output-text", "children"), [Input("input-text", "value")])def update_output(input_value): return f"Processed: {input_value}"with app.test_client() as client: rv = client.get("/") app.server.wait_for_reloader(timeout=5) res = client.post("/", data={"input-text": "hello"}) until(lambda: app.last_response is not None, timeout=10) assert app.last_response["output-text"] == "Processed: hello" 这个测试用例展示了如何通过模拟用户输入验证回调函数的正确性。通过app.test_client()获取客户端,可以独立测试Dash应用的功能。
转载地址:http://szlfk.baihongyu.com/