Skip to content

2014

Testing for the existence of a Flask request context

I just finished reviewing a pull request that contained an extraneous statement inside a try block.

Here's the code in question:

try:
    if signature not in g._celery_tasks:
        g._celery_tasks.append(signature)
except RuntimeError:
    signature()

While this code works fine, the RuntimeError being caught is expected to be raised when g._celery_tasks is accessed. Because g is a werkzeug.LocalProxy object, the exception is raised if there is no active request context. My concern was that if the next line raised a RuntimeError, it would also be caught. As this is not the intent of this handler catching such an error would be unexpected behavior.