Plotly / Dash - Python how to stop execution after time?

12,484

Since plotly uses flask for the server. So you code sys.exit("Bye!") is actually never reached, hence your server is never stopped. So there are 2 ways to stop your server,

  • Ctrl + c which I assume you would be doing now

  • Now you can do it using code too, so if you really need to stop the code after some time you should stop the flask server. To stop flask server you need to create a route. So whenever you hit that url the server would stop.

Following is the code is for Flask, you need to transform it to equivalent plotly code:

from flask import request

def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

Now you can shutdown the server by calling this function:

@app.route('/shutdown', methods=['POST'])
def shutdown():
    shutdown_server()
    return 'Server shutting down...'

Update: For plotly you can write the code in the following way.

import dash
import dash_core_components as dcc
import dash_html_components as html
from flask import request

print(dcc.__version__) # 0.6.0 or above is required

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    # represents the URL bar, doesn't render anything
    dcc.Location(id='url', refresh=False),

    dcc.Link('Navigate to "/"', href='/'),
    html.Br(),
    dcc.Link('Navigate to "/page-2"', href='/page-2'),

    # content will be rendered in this element
    html.Div(id='page-content')
])

def shutdown():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

@app.callback(dash.dependencies.Output('page-content', 'children'),
              [dash.dependencies.Input('url', 'pathname')])
def display_page(pathname):
    if pathname =='/shutdown':
        shutdown()
    return html.Div([
        html.H3('You are on page {}'.format(pathname))
    ])


if __name__ == '__main__':
    app.run_server(debug=True)
Share:
12,484
wieli99
Author by

wieli99

Updated on June 24, 2022

Comments

  • wieli99
    wieli99 almost 2 years

    I want to stop my Dash Program from executing after a certain amount of time (even better when I close the browser window, though I doubt that's possible). Is there a way to interrupt it through python?

    I already tried putting a

    sys.exit() 
    

    after calling app.run_server. Tough as far as I understand

    app.run_server
    

    is on an infinte loop, thus I'm never reaching sys.exit()

    if __name__ == '__main__':
        app.title = 'foo'
        app.run_server(debug=False)
        sys.exit("Bye!")