kc64 kc64 - 1 year ago 119
Python Question

Using Flask web app as Windows application

We have a web application developed using Flask that runs on a Windows server with clients that connect to it. We now have a use case where it is desired that the server and client be combined onto a laptop so that both server and client code run together and make it appear as a native Windows application.

Basically, we now have two requirements that we did not have before:
1. Must be able to launch the browser from within Python.
2. Must be able to terminate the Python (Flask) application on browser window close.

We have succeeded in item 1. Item 2 remains elusive. We have tried terminating the werkzeug server but the Python code keeps running. Seeking help from those that know.

Answer Source

After reading the docs more thoroughly and experimenting with the implementation, we found the following main code to satisfy the objective.

from multiprocessing import Process, freeze_support

def run_browser():
    import webbrowser
    chrome = webbrowser.get(r'C:\\Program\ Files\ (x86)\\Google\\Chrome\\Application\\chrome.exe --window-size=500,500 --app=%s')

def run_app():
    from app import webapp
    webapp.run() #debug=True) #, use_reloader=False)

if __name__ == '__main__':

    a = Process(target=run_app)
    a.daemon = True

    b = Process(target=run_browser)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download