我正在使用Flask构建一个Web应用程序。我已经对Flask对象进行了子类化,以便在应用程序退出之前( Flask对象被销毁)执行一段代码。当我在终端中运行它并按下^ C时,我没有看到" Can you hear me? "消息,因此我认为__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()
我希望这段代码能在析构函数中执行,以便无论应用程序如何加载都能运行。例如,在测试中运行
app.run()
,在生产环境中运行gunicorn hello.py
。谢谢!