2015-06-09 3 views
5

मैं फ्लास्क का उपयोग एक आरईएसटी एंडपॉइंट के रूप में कर रहा हूं जो एक कतार में एक आवेदन अनुरोध जोड़ता है। कतार तब एक दूसरे धागे से खपत होती है।पायथन फ्लास्क शट डाउन इवेंट हैंडलर

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) 

वहाँ फ्लास्क में बंद ईवेंट हैंडलर है ताकि मैं उसे सफाई से बंद उपभोक्ता धागा जब भी कुप्पी एप्लिकेशन बंद (जैसे जब अपाचे सेवा है पुन: प्रारंभ)?

उत्तर

8

कोई app.stop() वहाँ है कि है कि आप क्या देख रहे हैं, फिर भी मॉड्यूल atexit का उपयोग कर आप कुछ इसी तरह कर सकते हैं:

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

:

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

इस पर विचार करें नोट-atexit को भी कॉल नहीं किया जाएगा यदि आप Ctrl-C का उपयोग करके अपने सर्वर को मजबूर करते हैं।

इसके लिए एक और मॉड्यूल- signal है।

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

+5

मैं इसका उपयोग कर रहा हूं और यह अच्छी तरह से काम कर रहा है। धन्यवाद। वैसे, एटएक्सिट Ctrl C को ठीक से संभालता है – arturvt

संबंधित मुद्दे