Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Flask knows which decorated function to call?

So I'm going through the basic Flask tutorial, and looking at their code there's this snippet:

 @app.teardown_appcontext
 def close_db_connection(exception):
    """Closes the database again at the end of the request."""
    top = _app_ctx_stack.top
    if hasattr(top, 'sqlite_db'):
        top.sqlite_db.close()

Now, for what I've read in their manual, the function "app.teardown_appcontext" is called whenever one of the callbacks has an unexpected behavior. Decorating a function with it allows you to add functionality to the original function. Or at least that's what I understand from decorators. But, if I do this:

@app.teardown_appcontext
def stack_overflow_rocks(exception):
    """Closes the database again at the end of the request."""
    top = _app_ctx_stack.top
    if hasattr(top, 'sqlite_db'):
        top.sqlite_db.close()

It still works. How does Flask manages this?

My guess is that when I run the "flaskr.py" file with all the main code, it associates whatever decorated function with their code to call it when necessary. I tried reading a lot of sources about decorator to see if my interpretation is wrong, but could not find any mistake.

like image 717
diogocarmo Avatar asked Feb 12 '26 23:02

diogocarmo


1 Answers

As you can see in the code, the decorator adds the function you decorate with it to a list of functions (self.teardown_appcontext_funcs) on a Flask object instance (app in your case). This list is then iterated over in reverse order when the appcontext is torn down, with each function being passed the exception triggering the teardown, or a placeholder exception if none was raised. This happens in Flask.do_teardown_appcontext().

like image 170
Silas Ray Avatar answered Feb 14 '26 12:02

Silas Ray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!