Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask destructor

Tags:

python

flask

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!

like image 981
tweaksp Avatar asked Dec 25 '22 23:12

tweaksp


2 Answers

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 ...

like image 175
HolgerSchurig Avatar answered Dec 28 '22 13:12

HolgerSchurig


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.

like image 39
user2357112 supports Monica Avatar answered Dec 28 '22 13:12

user2357112 supports Monica