I'm building a web application using Flask. I've sub-classed the Flask object so that I can execute a chunk of code before the app exits (the Flask object get's destroyed). When I run this in my terminal and hit ^C, I'm not seeing the "Can you hear me?" message, so I assume that __del__()
isn't getting called.
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()
I'd like this code to execute in the destructor so that it'll run no matter how the application is loaded. i.e, app.run()
in testing, gunicorn hello.py
in production. Thanks!
Maybe this is possible:
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?'
I have, however, no clue if you can still use app
in the finally block ...
It is not guaranteed that __del__()
methods are called for objects that still exist when the interpreter exits. Also, __del__()
methods may not have access to global variables, since those may already have been deleted. Relying on destructors in Python is a bad idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With