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
Flask uses the term context local for this. Flask automatically pushes a request context when handling a request. View functions, error handlers, and other functions that run during a request will have access to the request proxy, which points to the request object for the current request.
has_app_context is a function in the flask. ctx module that is similar to has_request_context but for the application context rather than the request. after_this_request and has_request_context are a couple of other callables within the flask. ctx package that also have code examples.
A request context is just that: storage local to that request, and that is dropped once that request completes. You would typically authenticate a user and then store their userID in the context, or their preferred language, or a CSRF token, etc.
To access the incoming data in Flask, you have to use the request object. The request object holds all incoming data from the request, which includes the mimetype, referrer, IP address, raw data, HTTP method, and headers, among other things.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With