ergoithz ergoithz - 9 months ago 112
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/
171 self.manager = self.manager_module.PluginManager(
172 with
--> 173 self.manager.load_plugin('player')
174 self.assertIn(self.player_module.player,

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

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

Answer Source

The problem was elsewhere, pdb does not play well with flask current_app.


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():

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