Flask内的电流错误

2024-10-01 05:05:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我在我的flask应用程序上看到了一个相当奇怪的行为:嵌套的app_上下文在我的测试套件中不能正常工作,所以当前的应用程序localproxy没有指向正确的应用程序。它是完全同步的代码,所以没有线程,腐蚀或任何东西。在

有人能提供指导吗?在

> /.../browsepy/tests/deprecated/test_plugins.py(173)test_register_plugin()
    171         self.manager = self.manager_module.PluginManager(self.app)
    172         with self.app.app_context():
--> 173             self.manager.load_plugin('player')
    174         self.assertIn(self.player_module.player, self.app.blueprints.values())
    175 

ipdb> self.app
<Flask 'TestIntegration'>
ipdb> type(self.app)
<class 'flask.app.Flask'>
ipdb> d
> /.../browsepy/manager.py(151)load_plugin()
    149         module = super(RegistrablePluginManager, self).load_plugin(plugin)
    150         if hasattr(module, 'register_plugin'):
--> 151             module.register_plugin(self)
    152         return module
    153 

ipdb> current_app
<Flask 'browsepy'>
ipdb> type(current_app)
<class 'werkzeug.local.LocalProxy'>

Tags: pytestselfregisterapp应用程序flaskmanager
1条回答
网友
1楼 · 发布于 2024-10-01 05:05:40

问题出在其他地方,pdb不能很好地使用flask current_app。在

编辑

我运行的测试套件没有fail-fast选项,所以其他测试在注入事后调试程序之前运行。在

无论如何,flask的行为仍然是非常有问题的:它不会在使用后清理上下文全局变量app.test_客户端方法,这就是我试图调试的错误和发现的调试问题的根源。在

为了防止烧瓶本身在测试中混合来自不同应用的物质,我必须使用以下函数来清理烧瓶的上下文:

import flask


def clear_localstack(stack):
    '''
    Clear given werkzeug LocalStack instance.

    :param ctx: local stack instance
    :type ctx: werkzeug.local.LocalStack
    '''
    while stack.pop():
        pass


def clear_flask_context():
    '''
    Clear flask current_app and request globals.

    When using :meth:`flask.Flask.test_client`, even as context manager,
    the flask's globals :attr:`flask.current_app` and :attr:`flask.request`
    are left dirty, so testing code relying on them will probably fail.

    This function clean said globals, and should be called after testing
    with :meth:`flask.Flask.test_client`.
    '''
    clear_localstack(flask._app_ctx_stack)
    clear_localstack(flask._request_ctx_stack)

相关问题 更多 >