首页 > 解决方案 > Dash - 回调 - 从按钮启动脚本

问题描述

我正在尝试从破折号应用程序中的按钮启动 python 脚本。我尝试使用此处论坛上讨论的其他问题的见解,但我遇到了脚本在启动破折号应用程序时执行的问题。启动应用程序后,我可以单击,脚本将再次执行。但是,我需要阻止第一次启动,因为这会在我的数据库中创建不需要的数据负载。
查看plotly dash 文档,问题似乎来自在应用程序启动阶段执行回调的回调启动,我试图找出不同的方法来克服这个话题,但到目前为止还没有。

任何线索我可以修改我现有的或创建一个新的回调以避免这个问题,我猜你们中的一些人有同样的问题?

我的代码如下:

# -*- coding: utf-8 -*-
"""
Created on Mon Mar  2 10:36:21 2020

"""
import pathlib
import dash
import pandas as pd
from dash.dependencies import Input, Output, State
import dash_html_components as html
from dash.exceptions import PreventUpdate
import dash_table
import os

script_fn = 'test.py'

app = dash.Dash(__name__, meta_tags=[{"name": "viewport", "content": "width=device-width"}])

app.layout = html.Div(
                children=[html.Div((
                            html.Button('df1_Settlement 5i', id='button'),
                    html.Div(id='output-container-button',
                            children='Load new file'))
                    ),
                ],
            )

@app.callback(dash.dependencies.Output('output-container-button', 'children'),[dash.dependencies.Input('button', 'n_clicks')],prevent_initial_call=True)

def run_script_onClick(n_clicks):
    # Don't run unless the button has been pressed...
    if n_clicks is None:
        raise PreventUpdate 
    else:    
        exec(open(script_fn).read())
    
# Main
if __name__ == "__main__":
    app.run_server(debug=False)

标签: pythoncallbackplotly-dashscript

解决方案


尝试使用 if n_clicks 不是 None 和 n_clicks > 0 条件来自动触发回调。

import pathlib
import dash
import pandas as pd
from dash.dependencies import Input, Output, State
import dash_html_components as html
from dash.exceptions import PreventUpdate
import dash_table
import os

script_fn = 'test.py'

app = dash.Dash(__name__, meta_tags=[{"name": "viewport", "content": 
"width=device-width"}])

app.layout = html.Div(
                children=[html.Div((
                            html.Button('df1_Settlement 5i', id='button', 
                                         n_clicks = 0),
                            html.Div(id='output-container-button',
                                      children='Load new file'))
                    ),
                ],
            )

@app.callback(dash.dependencies.Output('output-container-button', 'children'), 
[dash.dependencies.Input('button', 'n_clicks')],prevent_initial_call=True)

def run_script_onClick(n_clicks):
    
    if n_clicks is not None and n_clicks > 0:
        exec(open(script_fn).read()) 
    else:    
        raise PreventUpdate Error
    
# Main
if __name__ == "__main__":
    app.run_server(debug=True)

推荐阅读