烧瓶析构

twe*_*ksp 4 python flask

我正在使用Flask构建一个Web应用程序.我已经对Flask对象进行了细分,这样我就可以在应用程序退出之前执行一大块代码(Flask对象被摧毁).当我在我的终端上运行这个并点击^ C时,我没有看到"你能听见我吗?" 消息,所以我假设__del__()没有被调用.

from flask import Flask

class MyFlask (Flask):

  def __init__(self, import_name, static_path=None, static_url_path=None,
                     static_folder='static', template_folder='templates',
                     instance_path=None, instance_relative_config=False):

    Flask.__init__(self, import_name, static_path, static_url_path,
                         static_folder, template_folder,
                         instance_path, instance_relative_config)

    # Do some stuff ... 

  def __del__(self):
    # Do some stuff ... 
    print 'Can you hear me?'

app = MyFlask(__name__)

@app.route("/")
def hello():
 return "Hello World!"

if __name__ == "__main__":
  app.run()
Run Code Online (Sandbox Code Playgroud)

我希望这个代码在析构函数中执行,这样无论应用程序如何加载它都会运行.即,app.run()在测试中,gunicorn hello.py在生产中.谢谢!

Hol*_*rig 6

也许这是可能的:

if __name__ == '__main__':
    init_db()  #or what you need
    try:
        app.run(host="0.0.0.0")
    finally:
        # your "destruction" code
        print 'Can you hear me?'
Run Code Online (Sandbox Code Playgroud)

但是,如果你仍然可以app在finally块中使用,我没有任何线索......