python - 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)
解决方案
尝试使用 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)
推荐阅读
- java - 使用 JSch 将文件内容下载到字符串
- android - Camera 2 API 会降低拍摄后的质量
- java - 是否可以为 API 范围定义特定尺寸?
- java - 使用 Spring JPA 如何从 DB 视图中读取多个参考数据
- linux - 如何将静态库嵌入到共享库中?
- reactjs - 将参数传递给 react-apollo-hooks useQuery
- flutter - 如果 Observable 发出事件,为什么 StreamBuilder 的 hasData 属性没有设置为 True?
- ios - 为什么无法进行物体内碰撞检测?
- express - Heroku 将“未定义”添加到 BASE_URL 环境变量
- spring-boot - 为多家供应商写一份合同