moses-palmer / pystray

GNU General Public License v3.0
463 stars 57 forks source link

Running pystray with flask #91

Closed cslehel closed 3 years ago

cslehel commented 3 years ago

Hi, ca i run pystray with flask ? I made the following application but wont stop when i want to close

def action_one():
    print( 'action one' )

def action_exit():
    icon.visible = False
    icon.stop()

icon = icon(
    name = 'Name',
    icon = generate_icon(),
    title = 'Title',
    menu = menu(
        item( 'one', action_one ),
        item( 'Exit', action_exit )
    )
)

def flaskThread():
    app = Flask( __name__ )
    @app.route( '/data', methods = [ 'POST' ] )
    def nothing():
        return 'Hello World!'
    app.run( host = '127.0.0.1', port = 8080, debug = False, use_reloader = False )

flask_thread = threading.Thread( name = 'Flask Thread', target = flaskThread)
flask_thread.daemon = True

try:
    flask_thread.start()
    icon.run()
finally:
    print( 'finally' )
    if ( flask_thread.isAlive() ):
        print( 'joining flask thread' )
        flask_thread.join()

print( 'exit' )

After the icon.stop() command i get the finally printed and joining flask thread but not the exit.

Thank you for your time.

moses-palmer commented 3 years ago

Thank you for your report.

I see no inherent problem with running pystray together with flask*, and i think your issue has nothing to do with this library.

After having destroyed the icon, you attempt to join your flask thread. This hangs, since you have not instructed flask to actually terminate. I have no experience with that library, but you will have to to make flask exit as well in action_exit.

cslehel commented 3 years ago

Thank you for your answer. Got it working.

app = Flask( __name__ )
flask_thread_kwargs = { 'host': '127.0.0.1', 'port': 8080, 'threaded': True, 'use_reloader': False, 'debug': False }

@app.route( '/', methods = [ 'GET' ] )
def nothing():
    return 'Hello World!'

try:
    flask_thread = threading.Thread( target = app.run, daemon = True, kwargs = flask_thread_kwargs ).start()
    icon.run()
finally:
    print( 'end' )

Flask will stop after

icon.visible = False
icon.stop()