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
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']()
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)
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()
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)
.