使用Python shelve模块触发注册登录功能时出现KeyError回溯问题求助
问题根因
你在使用shelve存储用户关联数据时,所有用户维度的存储(金币、武器、护甲)统一使用用户名作为索引key,但在注册、登录流程的金币读取代码中,错误传入了用户密码作为key去查询username2gold库,只要密码和用户名不一致,就会触发当前的KeyError报错。
修复步骤
修改代码中2处错误的查询逻辑:
- 找到
usereg函数中对应行的代码:
gold_balance = username2gold[user_password]
替换为:
gold_balance = username2gold[user_username]
- 找到
userlogin函数中对应行的代码:
gold_balance = username2gold[user_password]
替换为:
gold_balance = username2gold[user_username]
额外优化建议
usereg函数中你打开了username2armour、username2weapon两个shelve库,但使用完成后没有执行close()操作,会存在资源泄漏风险,建议补充关闭逻辑play函数中的输入校验逻辑存在语法错误:while request_to_play != 'y' or 'n'的判断条件永远为真,会导致用户即使输入正确也无法退出循环,建议修改为while request_to_play not in ('y', 'n')- 修复完成后建议先删除项目目录下旧的shelve生成的
.db/.dat/.dir文件,避免历史脏数据影响测试结果
内容的提问来源于stack exchange,提问作者DawsUTV
相关产品推荐
相关产品推荐

