Files
python-flask/project04/[任务书]基于文件的用户管理.md
2025-09-11 16:52:33 +08:00

79 lines
2.4 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 基于文件的用户管理
## 需求
### 数据库文件设计
- 创建db文件并且保存用户名、密码、剩余登录次数、解封的时间示例如下
```
user01|123456|3|1733039528
user02|123123|3|1733039528
user03|121212|2|1733039528
```
### 登录功能
- 用户输入正确的用户名和密码,就可以登录
- 用户输入错误的用户名,提示用户名不存在
- 用户名正确但是密码错误就提示密码错误输入错误3次就封号30秒
- 用户名正确只要是封号期间不管密码是否正确都提示已封号还有xx秒解封
- 用户名正确,如果已经解封,就正常登录
## 参考代码
```python
import time
# 数据库文件路径
db_file = 'db'
# 读取数据库文件,返回用户信息字典
users = {}
with open(db_file, 'a+') as file:
file.seek(0)
for line in file:
username, password, attempts, ban_time = line.strip().split('|')
users[username] = {
'password': password,
'attempts': int(attempts),
'ban_time': int(ban_time)
}
# 主程序
while True:
username = input("请输入用户名:")
if username not in users:
print("用户名不存在。")
continue
if users[username]['attempts'] <= 0 and users[username]['ban_time'] > int(time.time()):
remaining_time = users[username]['ban_time'] - int(time.time())
print(f"已封号,还有{remaining_time}秒解封。")
continue
password = input("请输入密码:")
if password == users[username]['password']:
users[username]['attempts'] = 3 # 重置尝试次数
print("登录成功。")
else:
users[username]['attempts'] -= 1
if users[username]['attempts'] == 0:
users[username]['ban_time'] = int(time.time()) + 30 # 封号30秒
print("密码错误账号已被封禁30秒。")
else:
print("密码错误,剩余尝试次数:", users[username]['attempts'])
# 将更新后的用户信息写回数据库文件
with open(db_file, 'w') as file:
for user, info in users.items():
file.write(f"{user}|{info['password']}|{info['attempts']}|{info['ban_time']}\n")
```
><span style="color: red; background: yellow; padding: 2px 5px; font-size: 22px;">作业4.1提交的内容</span>
>
>- 理解程序的运行逻辑
>- 程序运行成功的截图,单独发送给组长