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

时间:2016-10-27 12:38:52

标签: python logging flask werkzeug

我想在Flask请求期间记录时记录上下文变量(requestsession)中的一些数据,但是如果没有则使用默认行为。

我在try ... except中使用了logging.formatter块。有没有更好的方法来检查请求上下文?

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

1 个答案:

答案 0 :(得分:26)

使用has_request_contexthas_app_context

if has_request_context():
    # request is active

或者,current_appgrequestsession都是LocalProxy的实例。如果未绑定代理,则将其视为布尔值时为False

if request:
    # request is active