ergoithz ergoithz - 7 days ago 6
Python Question

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

Answer

The problem was elsewhere, pdb does not play well with 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.

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.

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)