28

I'm using Flask as a REST endpoint which adds an application request to a queue. The queue is then consumed by a second thread.

server.py

def get_application():
    global app
    app.debug = True
    app.queue = client.Agent()
    app.queue.start()                                                                                                                                                                                                                
    return app

@app.route("/api/v1/test/", methods=["POST"])
def test():
     if request.method == "POST":
        try:
           #add the request parameters to queue
           app.queue.add_to_queue(req)
        except Exception:
            return "All the parameters must be provided" , 400
     return "", 200

     return "Resource not found",404

client.py

class Agent(threading.Thread):

      def __init__(self):
          threading.Thread.__init__(self)
          self.active = True
          self.queue = Queue.Queue(0)


      def run(self):
           while self.active:
              req = self.queue.get()
              #do something


      def add_to_queue(self,request):
           self.queue.put(request)

Is there a shutdown event handler in flask so that I can cleanly shutdown the consumer thread whenever the flask app is shutdown (like when the apache service is restarted)?

Mark
  • 467
  • 2
  • 5
  • 12

1 Answers1

49

There is no app.stop() if that is what you are looking for, however using module atexit you can do something similar:

https://docs.python.org/2/library/atexit.html

Consider this:

import atexit
#defining function to run on shutdown
def close_running_threads():
    for thread in the_threads:
        thread.join()
    print "Threads complete, ready to finish"
#Register the function to be called on exit
atexit.register(close_running_threads)
#start your process
app.run()

Also of note-atexit will not be called if you force your server down using Ctrl-C.

For that there is another module- signal.

https://docs.python.org/2/library/signal.html

vvvvv
  • 25,404
  • 19
  • 49
  • 81
John
  • 2,410
  • 1
  • 19
  • 33
  • 15
    I'm using this and it's working well. Thanks. By the way, atexit handles the Ctrl C properly – arturvt Dec 27 '16 at 18:19
  • 3
    All this time -- never new about atexit, I'm in your debt. – SteveJ Nov 03 '18 at 13:40
  • this is a nice answer in the sense that it shows how to cleanup dangling unsupervised threads. However, it does not quite answer the question if flask by itself provides some signaling in the event of server-shutdown or similar. Also here thread control is outside the app itself (your variable `the_threads`) – mzoll May 12 '20 at 16:02
  • I am a little bit confused. How could we stop flask application other-than using Ctrl-C or kill -9 PID? – runzhi xiao Dec 02 '22 at 05:38
  • You could shutdown (sends a TERM), or kill the power (just rude) to your server or the script could error. – KDM Feb 27 '23 at 18:41