42

I want to log some data from context variables (request, session) when logging during a Flask request, but use default behavior if not.

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

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

1 Answer 1

74

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.