Skip to content

Instantly share code, notes, and snippets.

@adamgreg
Created November 18, 2021 12:29
Show Gist options
  • Save adamgreg/cc1abd2123cf820d9e71bf3afb5e63f5 to your computer and use it in GitHub Desktop.
Save adamgreg/cc1abd2123cf820d9e71bf3afb5e63f5 to your computer and use it in GitHub Desktop.
Presents a Dash app as a native application, like an Electron app. Pops up a minimal window locally and shuts down the server when that window is closed.
from dash import Dash, html
def show_in_native_window(app: Dash) -> None:
"""
Modify the application to launch a minimal browser window, and shut down when this window is closed,
to give the look & feel of a native application.
"""
from threading import Timer
import flask
import native_web_app # Available through pip: https://pypi.org/project/native-web-app/
# Add URL that can be used to shut down the Dash application
@app.server.route('/shutdown', methods=['GET', 'POST'])
def shutdown():
func = flask.request.environ.get('werkzeug.server.shutdown')
if func is not None:
func()
return ''
# Add Javascript that POSTs to the shutdown URL when the window is closed
shutdown_js = "window.addEventListener('pagehide', () => {navigator.sendBeacon('/shutdown');});"
app.config.external_scripts.append('data:,' + shutdown_js)
def open_native_window():
native_web_app.open('http://127.0.0.1:8050')
# Open the application in a local window once the Dash server has had some time to start
Timer(1, open_native_window).start()
# Start the Dash application
app.run_server()
def demo():
app = Dash('Native Dash App Demo')
app.layout = html.Div(['Hello world!'])
show_in_native_window(app)
if __name__ == '__main__':
demo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment