Streamlit登录报错:KeyError 'name'与timedelta类型错误的解决咨询
Streamlit登录报错:KeyError: 'name' 与 timedelta类型错误的成因及修复
错误成因
- 两个错误存在关联:
unsupported type for timedelta days component: str是根源,KeyError: 'name'是衍生问题。 - 核心原因是配置
streamlit-authenticator时,cookie过期天数(cookie_expiry_days)被设置为字符串类型(比如"7"而非7),导致认证模块内部创建timedelta对象时触发类型错误,直接中断了登录流程。 - 流程中断后,
st.session_state中本应被初始化的name、authentication_status、username等用户相关键未被正确写入,后续调用authenticator.login()返回时尝试读取这些键,就抛出了KeyError: 'name'。 - 额外可能的诱因:如果
credentials字典中某个用户缺失name字段,也会导致认证后无法写入st.session_state['name']。
修复步骤
- 修正cookie过期天数类型:检查
streamlit-authenticator初始化代码,确保cookie_expiry_days参数是整数而非字符串。示例:# 错误写法 authenticator = stauth.Authenticate(credentials, "cookie_name", "cookie_key", "7", "preauthorized") # 正确写法(将过期天数改为整数) authenticator = stauth.Authenticate(credentials, "cookie_name", "cookie_key", 7, "preauthorized") - 检查用户信息完整性:确认
credentials字典中每个用户都包含name字段,无缺失。示例:credentials = { "usernames": { "johndoe": { "name": "John Doe", # 必须存在且为字符串 "password": "hashed_password_here" }, "janedoe": { "name": "Jane Doe", "password": "another_hashed_password" } } } - 重置session状态并重启应用:关闭当前Streamlit服务,清除浏览器缓存(或用无痕窗口测试),避免旧的session残留导致异常。
- 添加容错判断(可选):在登录调用前先初始化session_state的相关键,防止读取失败:
# 初始化session_state默认值 if 'name' not in st.session_state: st.session_state['name'] = "" if 'authentication_status' not in st.session_state: st.session_state['authentication_status'] = None if 'username' not in st.session_state: st.session_state['username'] = "" # 执行登录 full_names, authentication_status, usernames = authenticator.login("Login", "main")
内容的提问来源于stack exchange,提问作者SomSin
相关产品推荐
相关产品推荐

