WillMorrison
WillMorrison

Reputation: 45

Flask Teardown Appcontext Too Many Arguments

I'm getting a strange error when trying to run my Flask app. I set the teardown_appcontext to be a function I have to close the database: app.teardown_appcontext(close_db). When I visit the site or initialize the database, I get the error: TypeError: close_db() takes 0 positional arguments but 1 was given.

In testing, I set the arguments for close_db to *arg and it worked without issues, but when I print *arg it returns None. Why is it angry about getting too many arguments if nothing is being passed to close_db?

Upvotes: 3

Views: 775

Answers (1)

wowo878787
wowo878787

Reputation: 176

As you decorated your close_db function with app.teardown_appcontext(), the close_db function will be appended to teardown_appcontext_funcs list.

Then when the application context tears down Flask will call do_teardown_appcontext() for you.

As we can see Flask source code: app.py

def do_teardown_appcontext(self, exc=_sentinel):
    if exc is _sentinel:
        exc = sys.exc_info()[1]
    for func in reversed(self.teardown_appcontext_funcs):
        func(exc)  <-- here
    appcontext_tearing_down.send(self, exc=exc)

In the place I marked an arrow above, it passed the argument exc. That means to avoid the TypeError exception, your close_db need an corresponding argument.

Upvotes: 5

Related Questions