2015-06-09 20 views
5

Sto utilizzando Flask come endpoint REST che aggiunge una richiesta di applicazione a una coda. La coda viene quindi consumata da un secondo thread.Gestore di eventi di chiusura Python Flask

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) 

Esiste un gestore evento di arresto nel pallone in modo che possa pulito spegnere il filo consumatore quando l'app pallone viene chiuso (come quando il servizio apache è rinnovate)?

risposta

8

Non c'è app.stop() se questo è quello che stai cercando, ma utilizzando il modulo atexit si può fare qualcosa di simile:

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

Considerate questo:

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() 

Inoltre, la nota atexit non verrà chiamata se si forza il server verso il basso utilizzando Ctrl-C.

Per quello c'è un altro modulo- signal.

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

+5

Sto usando questo e funziona bene. Grazie. A proposito, atexit gestisce correttamente Ctrl C – arturvt

Problemi correlati