【问题标题】:Python Flask shutdown event handlerPython Flask 关闭事件处理程序
【发布时间】:2015-08-24 16:42:32
【问题描述】:

我使用 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 服务时)干净地关闭使用者线程?

【问题讨论】:

    标签: python multithreading flask


    【解决方案1】:
    from flask import request
    
    BASE_URL = "http://127.0.0.1:5000"
    SHUTDOWN = "/shutdown"
    
    def shutdown_server():
        func = request.environ.get('werkzeug.server.shutdown')
        if func is None:
            raise RuntimeError('Not running with the Werkzeug Server')
        func()
    
    @app.route(SHUTDOWN, methods=['POST'])
    def shutdown():
        shutdown_server()
        return 'Server shutting down...'
    

    这里似乎提到了一种方法:- http://web.archive.org/web/20190706125149/http://flask.pocoo.org/snippets/67

    【讨论】:

      【解决方案2】:

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

      另外注意-atexit 如果您使用 Ctrl-C 强制关闭服务器,则不会调用。

      为此还有另一个模块-signal

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

      【讨论】:

      • 我正在使用它,它运行良好。谢谢。顺便说一句,atexit 正确处理 Ctrl C
      • 一直以来——atexit 从来都不是新鲜事,我欠你的债。
      • 这是一个很好的答案,因为它展示了如何清理悬空的无监督线程。但是,如果烧瓶本身在服务器关闭或类似情况下提供一些信号,它并不能完全回答这个问题。同样这里的线程控制在应用程序本身之外(你的变量the_threads
      猜你喜欢
      • 2012-11-25
      • 1970-01-01
      • 2021-11-18
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2019-02-15
      相关资源
      最近更新 更多