我正在使用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()
我希望这个代码在析构函数中执行,这样无论应用程序如何加载它都会运行。即,app.run()
在测试中,gunicorn hello.py
在生产中。谢谢!
答案 0 :(得分: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?'
但是,如果您仍然可以在finally块中使用app
,那么我没有任何线索......
答案 1 :(得分:4)
It is not guaranteed that __del__()
methods are called for objects that still exist when the interpreter exits.此外,__del__()
方法可能无法访问全局变量,因为这些变量可能已被删除。依赖Python中的析构函数是一个坏主意。