Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Flask request context is available

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 
like image 801
ubombi Avatar asked Oct 27 '16 12:10

ubombi


People also ask

How do I get the request context in Flask?

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.

What is CTX in Flask?

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.

What is the context of a request?

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.

How do you get the request object in Flask?

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.


1 Answers

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 
like image 154
davidism Avatar answered Sep 19 '22 15:09

davidism