开发者社区> 问答> 正文

Python烧瓶关闭事件处理程序

我使用Flask作为一个REST端点,它将一个应用程序请求添加到一个队列中。然后该队列被第二个线程使用。 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)

在flask中是否有一个关闭事件处理程序,这样我就可以在flask应用程序关闭的时候干净的关闭消费者线程(比如当apache服务重新启动的时候)? 问题来源StackOverflow 地址:/questions/59381111/flask-hook-for-system-exceptions

展开
收起
kun坤 2019-12-28 13:55:51 427 0
1 条回答
写回答
取消 提交回答
  • 没有app.stop()如果那是你要找的,但是使用模块atexit你可以做类似的事情: https://docs.python.org/2/library/atexit.html 考虑一下:

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

    如果使用Ctrl-C强制服务器关闭,也不会调用note-atexit。 为此,还有另一个模块——信号。 https://docs.python.org/2/library/signal.html

    2019-12-28 13:55:58
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载