Start a flask application in separate thread

前端 未结 4 437
粉色の甜心
粉色の甜心 2020-11-27 17:51

I\'m currently developing a Python application on which I want to see real-time statistics. I wanted to use Flask in order to make it easy to use and to underst

相关标签:
4条回答
  • 2020-11-27 18:14

    From the werkzeug documentation:

    Shutting Down The Server

    New in version 0.7.

    Starting with Werkzeug 0.7 the development server provides a way to shut down the server after a request. This currently only works with Python 2.6 and later and will only work with the development server. To initiate the shutdown you have to call a function named 'werkzeug.server.shutdown' in the WSGI environment:

    def shutdown_server(environ):
        if not 'werkzeug.server.shutdown' in environ:
            raise RuntimeError('Not running the development server')
        environ['werkzeug.server.shutdown']()
    
    0 讨论(0)
  • 2020-11-27 18:29

    If you are looking for accessing iPython terminal in Flask run your application in a separate thread. Try this example:

    from flask import Flask                                                         
    import thread
    
    data = 'foo'
    app = Flask(__name__)
    
    @app.route("/")
    def main():
        return data
    
    def flaskThread():
        app.run()
    
    if __name__ == "__main__":
        thread.start_new_thread(flaskThread, ())
    

    (Run this file in iPython)

    0 讨论(0)
  • 2020-11-27 18:35

    Updated answer for Python 3 that's a bit simpler:

    from flask import Flask                                                         
    import threading
    
    data = 'foo'
    app = Flask(__name__)
    
    @app.route("/")
    def main():
        return data
    
    if __name__ == "__main__":
        threading.Thread(target=app.run).start()
    
    0 讨论(0)
  • 2020-11-27 18:36

    You're running Flask in debug mode, which enables the reloader (reloads the Flask server when your code changes).

    Flask can run just fine in a separate thread, but the reloader expects to run in the main thread.


    To solve your issue, you should either disable debug (app.debug = False), or disable the reloader (app.use_reloader=False).

    Those can also be passed as arguments to app.run: app.run(debug=True, use_reloader=False).

    0 讨论(0)
提交回复
热议问题