python - How does Flask knows which decorated function to call? -
so i'm going through basic flask tutorial, , looking @ code there's snippet:
@app.teardown_appcontext def close_db_connection(exception): """closes database again @ end of request.""" top = _app_ctx_stack.top if hasattr(top, 'sqlite_db'): top.sqlite_db.close()
now, i've read in manual, function "app.teardown_appcontext" called whenever 1 of callbacks has unexpected behavior. decorating function allows add functionality original function. or @ least that's understand decorators. but, if this:
@app.teardown_appcontext def stack_overflow_rocks(exception): """closes database again @ end of request.""" top = _app_ctx_stack.top if hasattr(top, 'sqlite_db'): top.sqlite_db.close()
it still works. how flask manages this?
my guess when run "flaskr.py" file main code, associates whatever decorated function code call when necessary. tried reading lot of sources decorator see if interpretation wrong, not find mistake.
as can see in the code, decorator adds function decorate list of functions (self.teardown_appcontext_funcs
) on flask
object instance (app
in case). list iterated on in reverse order when appcontext torn down, each function being passed exception triggering teardown, or placeholder exception if none raised. happens in flask.do_teardown_appcontext()
.
Comments
Post a Comment