所以我用这种方式设置了我的烧瓶:
def create_app(config_name):
app = Flask(__name__, static_folder='../designs/UI', template_folder='../designs/UI', instance_relative_config=True)
app.config.from_object(app_config[config_name])
app.config.from_pyfile('config.py')
db.init_app(app)
login_manager.init_app(app)
login_manager.login_message = "You must be logged in to access this page."
login_manager.login_view = "auth.login_page"
migrate = Migrate(app, db)
from app import models
from .api import blueprint as api_blueprint
app.register_blueprint(api_blueprint, url_prefix='/api/v1.0')
@app.route('/')
def homepage():
return redirect('/api/v1.0')
return app
我的单元测试设置:
def setUp(self):
"""setup test variables"""
self.app = create_app(config_name="testing")
self.client = self.app.test_client
# binds the app with the current context
with self.app.app_context():
#create all tables
db.session.close()
db.drop_all()
db.create_all()
当我将模型导入测试文件并尝试访问数据库中的任何内容时,出现以下错误:
运行时错误:应用程序未在数据库实例上注册,并且没有应用程序绑定到当前上下文
有没有更好的方法来设置整个事情以便它可以工作?
我决定详细解释问题(和解决方案)。
1)为什么你的方法不起作用?因为你试图推动app context
using 上下文管理器。这是什么意思?current context
仅在内部可用with
堵塞。你绑定context
他只能在setUp
,但不在测试中。app
无需context
when setUp()
完成了。让我们看一下这个例子:
app = Flask(__name__)
class TestCase(TestCase):
def setUp(self):
with app.app_context():
# current_app is available(you will see <Flask 'app'> in terminal)
print current_app
# out of context manager - RuntimeError: Working outside of application context.
print current_app
def test_example(self):
pass
运行测试。你会看到 Flask 'app' + 异常。如果删除最后打印(超出with
block).
2)如何解决这个问题?你可以绑定app context
没有上下文管理器。
class TestCase(TestCase):
def setUp(self):
ctx = app.app_context()
ctx.push()
# after this you can use current_app
print current_app
def test_example(self):
# available because we pushed context in setUp()
print current_app
运行测试:
<Flask 'app'> # from setUp()
<Flask 'app'> # from test_example
那么,我们来总结一下。current_app
仅在上下文管理器“内部”可用。但是您可以在没有上下文管理器的情况下绑定上下文。
我希望我已经解释了细节并回答了您的问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)