简体   繁体   English

Flask app_context中的current_app错误

[英]Wrong current_app inside Flask app_context

I'm seeing a rather weird behavior on my flask application: nested app_contexts are not working as they should on my test suite, so current_app localproxy does not point to the correct app. 我在Flask应用程序上看到了一个相当奇怪的行为:嵌套的app_contexts无法像在我的测试套件上那样工作,因此current_app localproxy无法指向正确的应用程序。 It's fully synchronous code so no threads, corroutines or anything. 它是完全同步的代码,因此没有线程,例程或任何东西。

¿Could someone provide any guidance? ¿有人可以提供任何指导吗?

> /.../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'>

The problem was elsewhere, pdb does not play well with flask current_app. 问题出在其他地方,pdb在flask current_app中不能很好地运行。

EDIT 编辑

I was running the test suite without the fail-fast option, so other tests ran before injecting the post-mortem debugger. 我运行的测试套件没有fail-fast选项,因此在注入验尸调试器之前运行了其他测试。

Anyway, flask's behavior is still very problematic: it does not clean their context globals after using app.test_client methods, and that's the source of both error I tried to debug and the debug issue I found. 无论如何,flask的行为仍然很成问题:使用app.test_client方法后,它不会清除其上下文全局变量,这就是我尝试调试的错误和发现的调试问题的源头。

Here are the functions I had to use to clean flask's contexts in order to keep flask itself from mixing stuff from different applications on tests: 这是我必须使用的用于清理烧瓶上下文的函数,以防止烧瓶本身与测试中来自不同应用程序的内容混合在一起:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM