4

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!

tweaksp
  • 601
  • 5
  • 14
  • 3
    You should probably use [signals](http://docs.python.org/2/library/signal.html) in your script to catch the program ending. – korylprince Jul 22 '13 at 22:48
  • Good idea. It's easy enough to catch SIGINT, but I need to do some research on what signals will be used when the code is deployed. This is going to be put on Heroku. – tweaksp Jul 22 '13 at 23:10

2 Answers2

6

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

HolgerSchurig
  • 2,913
  • 2
  • 17
  • 9
4

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505