Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AppContext.pop() should use a different sentinel for the exception value. #1392

Closed
mjpieters opened this issue Mar 23, 2015 · 2 comments
Closed

Comments

@mjpieters
Copy link
Contributor

Consider the following:

from flask import Flask
app = Flask(__name__)

@app.teardown_appcontext
def teardown(exception):
    print exception

with app.app_context():
    try:
        raise ValueError()
    except ValueError:
        pass

Within the app.app_context() context (managed by with) an exception is raised and handled. However, the teardown_appcontext() handler is still passed the exception value.

That's because the exception was raised and handled within the same frame, and thus sys.exc_info() is still available. The AppContext.__exit__() method did pass in None for the exception value:

def __exit__(self, exc_type, exc_value, tb):
    self.pop(exc_value)

but the AppContext.pop() method cannot distinguish this from not passing in a value at all:

def pop(self, exc=None):
    """Pops the app context."""
    self._refcnt -= 1
    if self._refcnt <= 0:
        if exc is None:
            exc = sys.exc_info()[1]
        self.app.do_teardown_appcontext(exc)

This can easily be remedied by using a different sentinel default value:

_sentinel = object()

def pop(self, exc=_sentinel):
    """Pops the app context."""
    self._refcnt -= 1
    if self._refcnt <= 0:
        if exc is _sentinel:
            exc = sys.exc_info()[1]
        self.app.do_teardown_appcontext(exc)
@mjpieters
Copy link
Contributor Author

This applies to the request context as well, plus the app.do_teardown_request() and app.do_teardown_appcontext() methods. I'll create a pull request.

@untitaker
Copy link
Contributor

Fixed by #1393

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Nov 14, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants