KeyError: 'user_available'

KeyError: 'user_available'

我正在尝试检查用户是否可用然后呈现特定模板。我正在使用这种条件 if session['user_available']:,其中会话是从烧瓶中导入的。但是我收到 KeyError: 'user_available' 错误。如果不推荐使用此方法,那么用于评估当前用户使用会话的可用性的更新代码是什么。

请求时,会话中不存在 key-value 对。这会导致 KeyError。
本节的大部分内容将像听写一样使用。因此,您可以查询会话中是否存在 key-value 对。这应该假设即使密钥不是会话的一部分,也不会抛出 KeyError。

if 'user_available' in session and session['user_available']:
    # The key is present in the session and the value is set.