Flask撕裂Appcontext参数太多



我在尝试运行Flask应用程序时遇到一个奇怪的错误。我将teardown_appcontext设置为必须关闭数据库的函数:app.teardown_appcontext(close_db)。当我访问网站或初始化数据库时,我会得到错误:TypeError: close_db() takes 0 positional arguments but 1 was given

在测试中,我将close_db的参数设置为*arg,它正常工作,但当我打印*arg时,它返回None。如果没有任何东西传递给close_db,为什么它会对收到太多争论感到愤怒?

app.teardown_appcontext()修饰close_db函数时,close_db函数将附加到teardown_appcontext_funcs列表中。

然后,当应用程序上下文拆除时,Flask将为您调用do_teardown_appcontext()

正如我们所看到的Flask源代码: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)

在我在上面标记箭头的地方,它传递了参数exc。这意味着为了避免TypeError异常,您的close_db需要一个相应的参数。

最新更新