Hi there!
I’ve implemented a Dash-App where I trigger a folder listener (infinite while loop till file is found) via a callback on html.Button. If a user didn’t intend to click the respective button, how is it possible to “kill” or cancel the respective python process without shutting down the whole application. I’m quite new to dash as one may get the impression on reading my question …
I’m thinking about a solution involving a page refresh to cancel all fired callbacks or implementing an additional button to do so.
Many thanks in advance for your help!
PS: My callback is looking something like this:
@app.callback(Output('button2', 'style'),
[Input('button2', 'submit_n_clicks')],
[State('serialized-python-object', 'data')])
def update_output(submit_n_clicks, po_json):
if po_json is None:
raise PreventUpdate
if submit_n_clicks:
while not (os.path.exists(done_path + file_name):
pass
return {'color': colors['green'], 'width': 300}
else:
return {'color': colors['black'], 'width': 300}
I really don’t know if this can be achieved but you can try to use the same button that triggers the callback and use the variable submit_n_clicks like
if n_clicks %2==1:
while loop
else:
return None
So if they press it again it should return None
If not you can use a counter that increments with the while loop as an improvised timeout assuming it doesn’t affect performance
you can also use ctx=dash.callback_context
- it provides the state
of all callback parameters, including which button (if any) triggered the callback.
If I was to set the button style color to red for example if the user decided to cancel the respective calculation underlying to the button the change of the color is working of course. But I’m not sure if the actual python process (the underlying calculation) gets terminated as well which is what I’m trying to achive doing this. I don’t know how I would test this to be true or false, but when I’m running a pyhton script within the callback including selenium+chromedriver instead of the while loop I see that the python scripts keeps running even when the callback gets fired a second time and the button color changes to red. So I assume that the previous python process is still running in the background even when the second callback would not run any python code at all and simply return a different button style. This would look something like this:
from selenium import webdriver
@app.callback(Output('button2', 'style'),
[Input('button2', 'submit_n_clicks')],
[State('serialized-python-object', 'data')])
def update_output(submit_n_clicks, po_json):
if po_json is None:
raise PreventUpdate
if submit_n_clicks is None:
return {'color': colors['black'], 'width': 300}
if submit_n_clicks % 2 == 1:
driver = webdriver.Chrome(executable_path=dirver_path)
# do something with the driver and set button to green after its done ...
return {'color': colors['green'], 'width': 300}
else:
return {'color': colors['red'], 'width': 300}