180

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.

8
  • 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). Commented Mar 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". Commented Mar 22, 2013 at 5:42
  • @SeanVieira I want to know if there any solutions to do this.
    – vic
    Commented Mar 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.
    – vic
    Commented Mar 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. Commented Mar 22, 2013 at 11:40

21 Answers 21

203

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.

16
  • 28
    Do you know if there's any way to get the 'werkzeug.server.shutdown' property without needing a request context?
    – akatkinson
    Commented Oct 13, 2014 at 4:31
  • 5
    I had to change route method to 'GET' to get it to work.
    – C S
    Commented Aug 31, 2016 at 20:39
  • 7
    For 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) Commented Mar 4, 2017 at 0:59
  • 3
    Running flask as a Process doesn't work for me on Windows (pickling error since Windows can't fork), was your example run on Linux/MacOS?
    – dsfbmmg
    Commented Dec 30, 2020 at 0:51
  • 9
    btw, the first method has been deprecated now: github.com/pallets/werkzeug/pull/1873
    – aadibajpai
    Commented Jun 19, 2021 at 3:57
82

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.

9
  • 5
    I 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! Commented Sep 4, 2017 at 14:38
  • 1
    This seems to block on windows until I hit it with another request... any way around that?
    – Claudiu
    Commented Oct 12, 2017 at 19:45
  • I'm having the same issue as @Claudiu, except on Linux with python 3.6.2 Commented 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.
    – Eric Reed
    Commented Jul 22, 2020 at 21:41
  • 2
    In this case where do you put the endpoints?
    – Charalamm
    Commented Nov 18, 2021 at 6:23
41

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
1
  • 4
    I had to use sudo kill -9 28834 before the process could be killed.
    – Udo E.
    Commented Nov 2, 2020 at 15:51
21

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
2
  • 13
    I 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.
    – m3nda
    Commented Mar 29, 2017 at 7:12
  • 1
    Yeah I always do this Commented Dec 2, 2022 at 5:48
18

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
7
  • I tested your code, but after os.kill, the returned response cannot be received by the client. For curl, it outputs "curl: (56) Recv failure: Connection was reset". May see also Execute a function after Flask returns response to solve it.
    – samm
    Commented Apr 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?
    – Jurgy
    Commented May 11, 2020 at 12:33
  • Would an endpoint to shutdown the app not potentially cause a security risk with respect to availability? Commented Apr 28, 2023 at 18:21
  • I am using this code as the server.shutdown is deprecated. Before I do that, is this code okay to run in a production scenario? Commented Oct 24, 2023 at 15:06
  • 1
    Honestly, out of all the previous options, this seems like the best choice. It would be great if the Flask internals could have a way to finish out all current requests, reject new requests with 503, and then quit the process when zero requests are outstanding, but that's not the world we live in.
    – Jon Watte
    Commented Jul 3 at 14:52
15

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..."
1
  • 5
    this 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?
    – Juicy
    Commented May 28, 2017 at 20:35
14

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.

10

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)

9

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)
2
  • 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.
    – Expurple
    Commented Mar 12, 2021 at 11:18
  • my flaskapp is funny, even sigkill doesn't work
    – Dan D.
    Commented Feb 24, 2022 at 9:27
9

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)
1
  • 1
    a) explanation would be cool b) this does not send the "Done" back to the caller
    – flaschbier
    Commented Jan 1 at 10:55
4

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:

  1. These is shutdown endpoint which can be used for graceful shutdown. Note: it relies on request.environ.get which is usable only inside web request's context (inside @app.route-ed function)
  2. win32service's SvcStop method uses requests 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')
4

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 SIGTERM (3) or 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://localhost:8000/kill-backend and it'll fail with a connection refused error because the server is immediately dead.

5
  • 1
    Why do you use a global variable? Commented May 21, 2023 at 22:16
  • @WolfgangKuehn I use a global variable to avoid getting the request handler's PID, if I kill that only the one request will fail but the server will keep running, as it starts a process for each request. With the global variable containing the main process's PID I make sure to kill the main process.
    – Lampe2020
    Commented May 22, 2023 at 15:41
  • @Lampe2020 Actually, I get the same pid from the script global and the handle's scope. Besides, if Flask responds to each request with a separate process, the overhead would be too high.
    – Gary Wang
    Commented May 9 at 6:41
  • @GaryWang It may be threads, then. But still, killing the thread the request is handled in doesn't kill the server process. And when I wrote the above I didn't have as much experience in programming as I now have, as I'm still learning to program.
    – Lampe2020
    Commented May 9 at 22:17
  • @Lampe2020 As you call os.kill, you send terminate signal to the process instead of a thread. Once the process should exit, all handler threads and the main of the process is terminated.
    – Gary Wang
    Commented May 10 at 0:08
2

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.

How to kill a process running on particular port in Linux?

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.

0

You can use method bellow

app.do_teardown_appcontext()
2
  • 2
    This 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/…
    – rgov
    Commented Nov 16, 2020 at 1:32
  • 1
    this does not work for me
    – Neuron
    Commented Sep 26, 2021 at 13:07
0

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.

1
  • 1
    Please note: neither netstat nor grep will stop an active process.
    – poindexter
    Commented Mar 19, 2021 at 19:59
0
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"
1
  • 3
    Providing additional context regarding why & how this answer works works and when it should be used will improve its long-term value by helping readers.
    – outis
    Commented Feb 3, 2022 at 22:37
0

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
0

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.

0

you can try use

pkill python

pkill is a command-line utility that sends signals to the processes of a running program based on given criteria. The processes can be specified by their full or partial names, a user running the process, or other attributes.

The pkill command is a part of the procps (or procps-ng) package, which is pre-installed on nearly all Linux distributions. pkill is basicity a wrapper around the pgrep program that only prints a list of matching processes. How to Use the pkill Command

The syntax for the pkill command is as follows:

pkill [OPTIONS] <PATTERN>

The matching is specified using extended regular expressions.

When invoked without any option, pkill sends the 15 (TERM) signal to the PIDs of all running programs that match with the given name. For example, to gracefully stop all firefox processes, you would run:

pkill -15 python

The command returns 0 when at least one running process matches the requested name. Otherwise, the exit code is 1. This can be useful when writing shell scripts.

more info here

pkill-command-in-linux

-13

For Windows, it is quite easy to stop/kill flask server -

  1. Goto Task Manager
  2. Find flask.exe
  3. Select and End process
1
  • 36
    The power button on your computer is quite effective as well haha Commented Mar 9, 2020 at 17:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.