Flask Destructor

I am building a web application using Flask. I have subclassed the Flask object so that I can execute a piece of code before the application exits (the Flask object is destroyed). When I run this in my terminal and press ^ C, I don’t see β€œCan you hear me?”, So I assume that __del__() not 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 would like this code to be executed in the destructor, so that it works no matter how the application loads. those. app.run() when testing, gunicorn hello.py in production. Thanks!

+4
source share
2 answers

It is not guaranteed that the __del__() methods are invoked on objects that still exist when the interpreter exits. Also, __del__() methods may not have access to global variables, since they can already be deleted. Relying on destructors in Python is a bad idea.

+4
source

Perhaps 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, however, have no clue if you can still use the app in the finally block ...

+6
source

Source: https://habr.com/ru/post/1492804/


All Articles