检查Flask请求上下文是否可用

时间:2021-09-19 16:57:38

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

我想从上下文变量(请求、会话)中记录一些数据,当在Flask请求中进行日志记录时,如果不使用默认行为的话。

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

我正在尝试……除了logging.formatter块。是否有更好的方法检查请求上下文?

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

1 个解决方案

#1


16  

Use has_request_context or has_app_context.

使用has_request_context或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.

或者,current_app、g、请求和会话都是LocalProxy的实例。如果一个代理没有被绑定,当它被当作布尔值时,它将是假的。

if request:
    # request is active

#1


16  

Use has_request_context or has_app_context.

使用has_request_context或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.

或者,current_app、g、请求和会话都是LocalProxy的实例。如果一个代理没有被绑定,当它被当作布尔值时,它将是假的。

if request:
    # request is active