如何在视图外创建表单实例?
How can I create a form instance outside of a view?
我目前正在编写 Flask 应用程序。我的一个视图具有非常复杂的业务逻辑,因此我将其移至视图外声明的 class。在 class 的构造函数中,我创建了几个 flask_wtf.form.Form
对象的实例。
我的问题是在运行时出现以下错误:
*** RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in a way. To solve
this set up an application context with app.app_context(). See the
documentation for more information.
(ipdb
是我的)
我假设表单对象需要在视图中?但我想将创建它们的工作移到单独的 class 中,这样视图就不会变得太复杂,否则难以管理。
你不能。 flask_wtf.Form
需要应用上下文来设置 CSRF。
在将要使用的地方之外实例化表单实际上没有意义,因为您需要使用提交的数据来实例化它以执行任何有用的操作。
将创建表单实例转移到您调用该 class 的方法,而不是在它的 __init__
方法中。
我目前正在编写 Flask 应用程序。我的一个视图具有非常复杂的业务逻辑,因此我将其移至视图外声明的 class。在 class 的构造函数中,我创建了几个 flask_wtf.form.Form
对象的实例。
我的问题是在运行时出现以下错误:
*** RuntimeError: Working outside of application context.
This typically means that you attempted to use functionality that needed
to interface with the current application object in a way. To solve
this set up an application context with app.app_context(). See the
documentation for more information.
(ipdb
是我的)
我假设表单对象需要在视图中?但我想将创建它们的工作移到单独的 class 中,这样视图就不会变得太复杂,否则难以管理。
你不能。 flask_wtf.Form
需要应用上下文来设置 CSRF。
在将要使用的地方之外实例化表单实际上没有意义,因为您需要使用提交的数据来实例化它以执行任何有用的操作。
将创建表单实例转移到您调用该 class 的方法,而不是在它的 __init__
方法中。