I created a default basic web server with Flask from Visual Studio templates. When I launch it from the command prompt it says "Press Ctrl+C to quit". When I do press Ctrl+C, nothing happens and the server keeps running.
Question: Is there a way to make Flask stop on Ctrl+C as advertised?
This is the code of server startup:
from os import environ
from myapp import app
if __name__ == '__main__':
HOST = environ.get('SERVER_HOST', 'localhost')
try:
PORT = int(environ.get('SERVER_PORT', '5555'))
except ValueError:
PORT = 5555
app.run(HOST, PORT)
To stop a Flask server running on Windows: Ctrl + c. If Flask is still running, try: Ctrl + Break.
In my case, I found out that right ctrl + c does the trick in anaconda3 powershell - so no remapping necessary - I'm on Windows 10.
To stop a Flask server running on Windows:
taskkill /f /im python.exe
You can also select a specific Python process to kill:
> tasklist /fi "imagename eq python.exe"
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
python.exe 1080 Console 8 72,456 K
python.exe 15860 Console 8 73,344 K
> taskkill /F /pid 15860
SUCCESS: The process with PID 15860 has been terminated.
from flask import request
def shutdown_server():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
@app.route('/shutdown', methods=['POST'])
def shutdown():
shutdown_server()
return 'Server shutting down...'
sudo pkill -f "flask"
of course this will have some cons, since it's a kill command. If you have multiple flask instances running, it will kill ALL of them, just as most of the other kill commands. To get around this, you can make a route that is used to programically shutdown the flask server.
@app.route('/shutdown')
def shutdown():
sys.exit()
os.exit(0)
return
What his does; is, it will exit the program whenever /shutdown is triggered.
Of course this will need security, so no-random can spam shutdown your server.
Lets say you have a session called session['logged_in']
you would want to check if this session is True before shutting down the server.
Below should be working:
@app.route('/shutdown')
def shutdown():
# If not logged in, return back to the login page.
if not session or not session['logged_in']:
return render_template('loginpage.html')
# Logged_in, continue...
sys.exit()
os.exit(0)
return
Hopefully this helped
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With