注册和登录功能单用户版
注册
count = 0
while count < 3:
username_inp = input('请输入你的用户名:')
pwd_inp = input('请输入你的密码:')
re_pwd_inp = input('请再次输入密码:')
if not pwd_inp == re_pwd_inp:
print('两次输入的密码不一致')
count += 1
continue
with open('user_info.txt','w',encoding='utf8') as fa:
fa.write(f'{username_inp}:{pwd_inp}\n')
fa.flush()
break
登录
username_inp = input('请输入你的用户名:')
pwd_inp = input('请输入你的密码:')
with open('user_info.txt','r',encoding='utf8') as fr:
for user_info in fr:
username,pwd = user_info.split(':')
if username.strip() == username_inp and pwd.strip() == pwd_inp:
print('登录成功')
break
else:
continue
else:
print('用户名或密码错误')
注册和登录功能防攻击版
打开用户名和密码信息库
import time
with open('user_info.txt', 'r', encoding='utf8') as fr: # 打开信息表
ls = fr.read().split('|') # 取出信息放入列表
ls1 = ls[0:-1]
dic_username = {}
for user_info in ls1: # 把信息列表转换成字典
ls2 = user_info.split(':')
dic_username[ls2[0]] = ls2[1]
注册
count = 0
while count < 3:
user_name = input('请输入用户名:')
if user_name in dic_username: # 判断用户名是否重名
print('该用户名已被注册,请用其他用户名')
if count == 2: # 限制次数,防止恶意攻击
print('超过三次,等一分钟后再试')
time.sleep(5) # 休眠5秒钟
count = 0 # 再次启动当前while循环
else:
pwd_inp = input('请输入密码:')
re_pwd_inp = input('请再次输入密码:')
if not pwd_inp == re_pwd_inp:
print('两次输入的密码不一致')
if count == 2: # 限制次数,防止恶意攻击
print('超过三次,等一分钟后再试')
time.sleep(5) # 休眠5秒钟
count = 0 # 再次启动当前while循环
else:
with open('user_info.txt','a',encoding='utf8') as fa:
fa.write(f'{user_name}:{pwd_inp}|')
print('注册成功')
fa.flush()
break
count += 1 # 注意这一步的缩进层级
登录
count_login = 0
while count_login < 3:
username_inp = input('请输入你的用户名:')
pwd_inp = input('请输入你的密码:')
key_name = username_inp.strip()
value_pwd = pwd_inp.strip()
if key_name in dic_username and dic_username[key_name] == value_pwd:
print('登录成功')
else:
print('用户名或密码错误')
if count_login == 2: # 限制次数,防止恶意攻击
print('超过三次,请一分钟后再试')
time.sleep(5) # 休眠5秒钟
count_login = 0 # 再次启动当前while循环
count_login += 1