破折号:"Lock" 执行触发功能时的按钮
Dash: "Lock" Button while triggered function is executed
我有以下问题:
在我的 Plotly Dash 应用程序中,有一个由按钮触发的功能,最多可能需要 30 秒才能完成执行。
我现在的问题是,该功能可以通过单击按钮第二次触发,同时仍会执行第一次。
举个例子:
import dash
from dash.dependencies import Input, Output
import dash_html_components as html
import time
app = dash.Dash()
app.layout = html.Div([
html.H2('Imports'),
html.Button('Button', id='button'),
html.H3(id='button-clicks'),
])
@app.callback(
Output('button-clicks', 'children'),
[Input('button', 'n_clicks')]
)
def import_data(n_clicks):
if n_clicks:
for t in range(0, 10):
print(t)
time.sleep(1)
return 'Button has been clicked {} times'.format(n_clicks)
if __name__ == '__main__':
app.run_server(debug=True)
当我点击我的按钮时,输出将如我所愿:
0
1个
2个
3个
4
但是当我在例如 2 秒内点击按钮两次时,输出将是:0
1个
2个
0
3个
1个
4个
2个
3个
4,因为它正在并行执行我的 import_data 函数两次。
有什么方法可以防止这种并行执行(例如锁定按钮)?
THX & BR
我不确定您使用的是哪个版本的 Flask,但您的情况似乎默认启用了 threaded
参数。当启用 threaded
参数时,Flask 会同时处理请求。
尝试禁用它,
app.run_server(debug=True, threaded=false)
我有以下问题: 在我的 Plotly Dash 应用程序中,有一个由按钮触发的功能,最多可能需要 30 秒才能完成执行。
我现在的问题是,该功能可以通过单击按钮第二次触发,同时仍会执行第一次。
举个例子:
import dash
from dash.dependencies import Input, Output
import dash_html_components as html
import time
app = dash.Dash()
app.layout = html.Div([
html.H2('Imports'),
html.Button('Button', id='button'),
html.H3(id='button-clicks'),
])
@app.callback(
Output('button-clicks', 'children'),
[Input('button', 'n_clicks')]
)
def import_data(n_clicks):
if n_clicks:
for t in range(0, 10):
print(t)
time.sleep(1)
return 'Button has been clicked {} times'.format(n_clicks)
if __name__ == '__main__':
app.run_server(debug=True)
当我点击我的按钮时,输出将如我所愿: 0 1个 2个 3个 4
但是当我在例如 2 秒内点击按钮两次时,输出将是:0 1个 2个 0 3个 1个 4个 2个 3个 4,因为它正在并行执行我的 import_data 函数两次。
有什么方法可以防止这种并行执行(例如锁定按钮)?
THX & BR
我不确定您使用的是哪个版本的 Flask,但您的情况似乎默认启用了 threaded
参数。当启用 threaded
参数时,Flask 会同时处理请求。
尝试禁用它,
app.run_server(debug=True, threaded=false)