我想在 Flask 请求期间记录时从上下文变量(request
、session
)记录一些数据,但如果不是,则使用默认行为。
我在 logging.formatter
中使用 try ... except
block 。有没有更好的方法来检查请求上下文?
try:
record.user = session['user_name']
record.very_important_data = request.super_secret
except Exception:
record.user = None
最佳答案
使用 has_request_context
或 has_app_context
.
if has_request_context():
# request is active
或者,current_app
、g
、request
和 session
都是 LocalProxy< 的实例
。如果代理没有绑定(bind),当被视为 bool 值时,它将是False
。
if request:
# request is active
关于python - 检查 Flask 请求上下文是否可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40284800/