ubombi ubombi - 1 year ago 108
Python Question

Check if Flask request context is available

I want to log some data from context variables (

) when logging during a Flask request, but use default behavior if not.

I'm using a
try ... except
block in
. Is there a better way to check for a request context?

record.user = session['user_name']
record.very_important_data = request.super_secret
except Exception:
record.user = None

Answer Source

Use has_request_context or has_app_context.

if has_request_context():
    # request is active

Alternatively, current_app, g, request, and session are all instances of LocalProxy. If a proxy is not bound, it will be False when treated as a boolean.

if request:
    # request is active
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download