I want to implement a command which can stop flask application by using flask-script.
I have searched the solution for a while. Because the framework doesn't provide app.stop()
API, I am curious about how to code this. I am working on Ubuntu 12.10 and Python 2.7.3.
-
Why do you need to be able to stop your application from a script? (The best tool for the job will depend on what you are trying to do).– Sean VieiraMar 22, 2013 at 5:14
-
Seriously, what are you trying to do here? If you are talking about devserver for development, it is perfectly fine to stop it like that. In production you don't deploy like this and you can stop a request at any time you want, so the "app stops running".– Ignas ButėnasMar 22, 2013 at 5:42
-
@SeanVieira I want to know if there any solutions to do this.– vicMar 22, 2013 at 8:51
-
@IgnasB. I am developing a RESTful service on my machine right now. I am working on a project maybe it will help me to choose which machines should I deploy.The only way I can figure out is shutdown by killing the process.– vicMar 22, 2013 at 8:56
-
3@vrootic, but you will not use app.run() in production anyway. app.run() is used only for development and to test your application while developing. There are different ways how to run Flask in production, more can be found here for example flask.pocoo.org/docs/quickstart/#deploying-to-a-web-server And if you deploy somehow like that already (so I misunderstood question), the way to stop serving request coming to Flask is to stop http server which is serving it.– Ignas ButėnasMar 22, 2013 at 11:40
20 Answers
If you are just running the server on your desktop, you can expose an endpoint to kill the server (read more at Shutdown The Simple Server):
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.get('/shutdown')
def shutdown():
shutdown_server()
return 'Server shutting down...'
Here is another approach that is more contained:
from multiprocessing import Process
server = Process(target=app.run)
server.start()
# ...
server.terminate()
server.join()
Let me know if this helps.
-
26Do you know if there's any way to get the 'werkzeug.server.shutdown' property without needing a request context? Oct 13, 2014 at 4:31
-
5
-
7For completeness this answer is missing the function you would call outside of a request context to do the shutdown, which would be nothing more than a HTTP request to the server (which can originate from/to localhost) Mar 4, 2017 at 0:59
-
3Running flask as a
Process
doesn't work for me on Windows (pickling error since Windows can'tfork
), was your example run on Linux/MacOS? Dec 30, 2020 at 0:51 -
8btw, the first method has been deprecated now: github.com/pallets/werkzeug/pull/1873 Jun 19, 2021 at 3:57
I did it slightly different using threads
from werkzeug.serving import make_server
class ServerThread(threading.Thread):
def __init__(self, app):
threading.Thread.__init__(self)
self.server = make_server('127.0.0.1', 5000, app)
self.ctx = app.app_context()
self.ctx.push()
def run(self):
log.info('starting server')
self.server.serve_forever()
def shutdown(self):
self.server.shutdown()
def start_server():
global server
app = flask.Flask('myapp')
# App routes defined here
server = ServerThread(app)
server.start()
log.info('server started')
def stop_server():
global server
server.shutdown()
I use it to do end to end tests for restful api, where I can send requests using the python requests library.
-
4I did not manage to get the other stuff to work but this solution works great! Thanks a ton! For the other people: it also works with flask restful! Sep 4, 2017 at 14:38
-
1This seems to block on windows until I hit it with another request... any way around that?– ClaudiuOct 12, 2017 at 19:45
-
I'm having the same issue as @Claudiu, except on Linux with python 3.6.2 Nov 19, 2017 at 0:23
-
I don't know why this isn't accepted, but it seems to be the cleanest and works great without any extra dependencies. Thanks so much. Jul 22, 2020 at 21:41
-
1
This is a bit old thread, but if someone experimenting, learning, or testing basic flask app, started from a script that runs in the background, the quickest way to stop it is to kill the process running on the port you are running your app on. Note: I am aware the author is looking for a way not to kill or stop the app. But this may help someone who is learning.
sudo netstat -tulnp | grep :5001
You'll get something like this.
tcp 0 0 0.0.0.0:5001 0.0.0.0:* LISTEN 28834/python
To stop the app, kill the process
sudo kill 28834
-
3
My method can be proceeded via bash terminal/console
1) run and get the process number
$ ps aux | grep yourAppKeywords
2a) kill the process
$ kill processNum
2b) kill the process if above not working
$ kill -9 processNum
-
11I am nearly sure that the question is not "how to kill a process", and the problem is that doing ctrl+c doesn't kill it. Btw, i do use
kill -9 `lsof -i:5000 -t`
cuz no other than just 1 app can use the port and is being easy.– m3ndaMar 29, 2017 at 7:12 -
1
As others have pointed out, you can only use werkzeug.server.shutdown
from a request handler. The only way I've found to shut down the server at another time is to send a request to yourself. For example, the /kill
handler in this snippet will kill the dev server unless another request comes in during the next second:
import requests
from threading import Timer
from flask import request
import time
LAST_REQUEST_MS = 0
@app.before_request
def update_last_request_ms():
global LAST_REQUEST_MS
LAST_REQUEST_MS = time.time() * 1000
@app.post('/seriouslykill')
def seriouslykill():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
return "Shutting down..."
@app.post('/kill')
def kill():
last_ms = LAST_REQUEST_MS
def shutdown():
if LAST_REQUEST_MS <= last_ms: # subsequent requests abort shutdown
requests.post('http://localhost:5000/seriouslykill')
else:
pass
Timer(1.0, shutdown).start() # wait 1 second
return "Shutting down..."
-
4this works but feels... very hacky. I know it's been a while, but did you ever find a clean way of doing this, without sending a request to yourself?– JuicyMay 28, 2017 at 20:35
This is an old question, but googling didn't give me any insight in how to accomplish this.
Because I didn't read the code here properly! (Doh!)
What it does is to raise a RuntimeError
when there is no werkzeug.server.shutdown
in the request.environ
...
So what we can do when there is no request
is to raise a RuntimeError
def shutdown():
raise RuntimeError("Server going down")
and catch that when app.run()
returns:
...
try:
app.run(host="0.0.0.0")
except RuntimeError, msg:
if str(msg) == "Server going down":
pass # or whatever you want to do when the server goes down
else:
# appropriate handling/logging of other runtime errors
# and so on
...
No need to send yourself a request.
You don't have to press CTRL + C, but you can provide an endpoint which does it for you:
from flask import Flask, jsonify, request
import json, os, signal
@app.route('/stopServer', methods=['GET'])
def stopServer():
os.kill(os.getpid(), signal.SIGINT)
return jsonify({ "success": True, "message": "Server is shutting down..." })
Now you can just call this endpoint to gracefully shutdown the server:
curl localhost:5000/stopServer
-
I tested your code, but after
os.kill
, the returned response cannot be received by the client. Forcurl
, it outputs "curl: (56) Recv failure: Connection was reset". May see also Execute a function after Flask returns response to solve it.– sammApr 2, 2020 at 10:03 -
@samm, the conclusion from that question is that is not possible unless you start a different thread, right? Then how do you shut down the flask server from that different thread?– JurgyMay 11, 2020 at 12:33
If you're working on the CLI and only have one flask app/process running (or rather, you just want want to kill any flask process running on your system), you can kill it with:
kill $(pgrep -f flask)
If you're outside the request-response handling, you can still:
import os
import signal
sig = getattr(signal, "SIGKILL", signal.SIGTERM)
os.kill(os.getpid(), sig)
-
Nice one, thanks. I needed to add some cleanup code before terminating on Ctrl+C, so I created a SIGINT handler, which does the job and then calls your code.– ExpurpleMar 12, 2021 at 11:18
-
request.environ.get
deprecated.
Pavel Minaev solution is pretty clear:
import os
from flask import Flask
app = Flask(__name__)
exiting = False
@app.route("/exit")
def exit_app():
global exiting
exiting = True
return "Done"
@app.teardown_request
def teardown(exception):
if exiting:
os._exit(0)
If someone else is looking how to stop Flask server inside win32 service - here it is. It's kinda weird combination of several approaches, but it works well. Key ideas:
- These is
shutdown
endpoint which can be used for graceful shutdown. Note: it relies onrequest.environ.get
which is usable only inside web request's context (inside@app.route
-ed function) - win32service's
SvcStop
method usesrequests
to do HTTP request to the service itself.
myservice_svc.py
import win32service
import win32serviceutil
import win32event
import servicemanager
import time
import traceback
import os
import myservice
class MyServiceSvc(win32serviceutil.ServiceFramework):
_svc_name_ = "MyServiceSvc" # NET START/STOP the service by the following name
_svc_display_name_ = "Display name" # this text shows up as the service name in the SCM
_svc_description_ = "Description" # this text shows up as the description in the SCM
def __init__(self, args):
os.chdir(os.path.dirname(myservice.__file__))
win32serviceutil.ServiceFramework.__init__(self, args)
def SvcDoRun(self):
# ... some code skipped
myservice.start()
def SvcStop(self):
"""Called when we're being shut down"""
myservice.stop()
# tell the SCM we're shutting down
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STOPPED,
(self._svc_name_, ''))
if __name__ == '__main__':
os.chdir(os.path.dirname(myservice.__file__))
win32serviceutil.HandleCommandLine(MyServiceSvc)
myservice.py
from flask import Flask, request, jsonify
# Workaround - otherwise doesn't work in windows service.
cli = sys.modules['flask.cli']
cli.show_server_banner = lambda *x: None
app = Flask('MyService')
# ... business logic endpoints are skipped.
@app.route("/shutdown", methods=['GET'])
def shutdown():
shutdown_func = request.environ.get('werkzeug.server.shutdown')
if shutdown_func is None:
raise RuntimeError('Not running werkzeug')
shutdown_func()
return "Shutting down..."
def start():
app.run(host='0.0.0.0', threaded=True, port=5001)
def stop():
import requests
resp = requests.get('http://0.0.0.0:5001/shutdown')
You can use method bellow
app.do_teardown_appcontext()
-
2This is an incorrect guess. This function does not stop the app, it is called automatically to release some context at the end of processing an individual request. flask.palletsprojects.com/en/1.1.x/api/…– rgovNov 16, 2020 at 1:32
-
1
A Python solution
Run with: python kill_server.py
.
This is for Windows only. Kills the servers with taskkill, by PID, gathered with netstat.
# kill_server.py
import os
import subprocess
import re
port = 5000
host = '127.0.0.1'
cmd_newlines = r'\r\n'
host_port = host + ':' + str(port)
pid_regex = re.compile(r'[0-9]+$')
netstat = subprocess.run(['netstat', '-n', '-a', '-o'], stdout=subprocess.PIPE)
# Doesn't return correct PID info without precisely these flags
netstat = str(netstat)
lines = netstat.split(cmd_newlines)
for line in lines:
if host_port in line:
pid = pid_regex.findall(line)
if pid:
pid = pid[0]
os.system('taskkill /F /PID ' + str(pid))
# And finally delete the .pyc cache
os.system('del /S *.pyc')
If you are having trouble with favicon / changes to index.html loading (i.e. old versions are cached), then try "Clear Browsing Data > Images & Files" in Chrome as well.
Doing all the above, and I got my favicon to finally load upon running my Flask app.
Google Cloud VM instance + Flask App
I hosted my Flask Application on Google Cloud Platform Virtual Machine.
I started the app using python main.py
But the problem was ctrl+c did not work to stop the server.
This command $ sudo netstat -tulnp | grep :5000
terminates the server.
My Flask app runs on port 5000 by default.
Note: My VM instance is running on Linux 9.
It works for this. Haven't tested for other platforms. Feel free to update or comment if it works for other versions too.
-
1Please note: neither netstat nor grep will stop an active process. Mar 19, 2021 at 19:59
app = MyFlaskSubclass()
...
app.httpd = MyWSGIServerSubclass()
...
@app.route('/shutdown')
def app_shutdown():
from threading import Timer
t = Timer(5, app.httpd.shutdown)
t.start()
return "Server shut down"
-
1Providing additional context regarding why & how this answer works works and when it should be used will improve its long-term value by helping readers.– outisFeb 3, 2022 at 22:37
My bash script variant (LINUX):
#!/bin/bash
portFind="$1"
echo "Finding process on port: $portFind"
pid=$(netstat -tulnp | grep :"$1" | awk '{print $7}' | cut -f1 -d"/")
echo "Process found: $pid"
kill -9 $pid
echo "Process $pid killed"
Usage example:
sudo bash killWebServer.sh 2223
Output:
Finding process on port: 2223
Process found: 12706
Process 12706 killed
If the port is known (e.g., 5000) a simple solution I have found is to enter:
fuser -k 5000/tcp
this will kill the process on port 5000.
I found that killing the own PID seems to work, like follows:
import os
from flask import Flask
app = Flask(__name__)
own_pid = os.getpid() # Get the main process's PID in a global variable
@app.route('/kill-backend')
def kill_backend():
global own_pid # Make sure to use the global variable
os.kill(own_pid, 9) # The second argument is the signal, 9 stands for SIGKILL.
#If you want to "politely ask" the server to quit you can use SIGQUIT (15) instead.
app.run(host='0.0.0.0', port=8000)
I have tested this on Ubuntu 22.04 LTS and on Window$ 10. It works on both.
To trigger the server kill, just request http://127.0.0.1/kill-backend
and it'll fail with a connection refused
error because the server is immediately dead.
The problem is that the werkzeug BaseWSGIServer
instance created by werkzeug.serving.run_simple()
(which is called by app.run()
) is not made accessible. Yet this class does define a clean shutdown()
method that effectively terminates the server's mainloop without any hacks.
So if we can get access to that instance, we can kill the server. One way I can think of doing that is through the garbage collector's object tracking:
@app.route("/shutdown", methods=["POST"])
def shutdown():
for obj in gc.get_objects():
try:
if isinstance(obj, BaseWSGIServer):
obj.shutdown()
return "bye"
except:
pass
return "failed"
I found myself needing this to emulate making POST callbacks in my unit tests. With this function I can run the flask server in a thread and not worry about it staying alive while I run my other tests.
For Windows, it is quite easy to stop/kill flask server -
- Goto Task Manager
- Find flask.exe
- Select and End process
-
31The power button on your computer is quite effective as well haha Mar 9, 2020 at 17:36