编写登录接口(txt文件存储信息)
----目标----
·输入用户名密码
·认证成功后显示欢迎信息
·输错三次后锁定
----流程----
1.输入用户名,密码
2.检测用户是否注册
3.检测用户是否锁定
4.检测用户名和密码是否和注册信息相同
5.登录成功,欢迎提示
----构成----
2个文件:
username_password.txt:用来存放用户名和密码
lock_username.txt:用来存放锁定用户的名单
检查用户是否注册的函数: check_username_isExist()
检测用户是否锁定的函数: check_username_isLock()
检查密码是否正确的函数: check_password(wrong_times)
输错三次写入锁定名单的函数: write_lockusername()
----代码----
user_name = ""
password = ""
count = 0#登录循环
wrong_times= 0#输错密码次数
#------------------检查该用户是否注册-----------------
def check_username_isExist():
isExist = 0#0为未注册;1为已注册
with open(r"C:\Users\10524\PycharmProjects\untitled\t1\username_password.txt")as file1:#打开有用户名和密码的文件
user_list = file1.readlines()#读取到user_list
for List_user_pw in user_list:
(user, password1) = List_user_pw.strip("\n").split(" ")#标注文件中用户名和密码
if user_name == user:
isExist = 1
return isExist
#-----------------检查该用户是否被锁定------------------
def check_username_isLock():
with open(r"C:\Users\10524\PycharmProjects\untitled\t1\lock_username.txt")as file2: #打开有用户被锁定名单的文件
locklist = file2.readlines()#读取到lock_list
for lock_name in locklist:
username = lock_name.strip("\n")#标注文件中用户名
if user_name == username:
print("The user is locked!")
exit()
return
#------------------检查密码是否正确-----------------
def check_password(wrong_times):
with open(r'C:\Users\10524\PycharmProjects\untitled\t1\username_password.txt')as file:#打开有用户名和密码的文件
list = file.readlines()#读取到list
for user in list:
(username,passsword1) = user.strip("\n").split(" ")#标注文件中用户名和密码
if user_name == username and password == passsword1:
print("login successfully...")#登录成功
exit()
elif user_name == username and password != passsword1:
wrong_times+=1#密码不一致,错误次数加一
print("The password is error!")#登陆失败
return wrong_times
#将输错次数达三次的用户名写入锁定文件
def write_lockusername():
file = open("lock_username.txt", "a")
file.write('''\n{a}'''.format(a = user_name))
return
#------------------主程序-----------------
while count == 0:
print("Welcome to login")
user_name = input("username:")
password = input("password:")#输入用户名和密码
#ret =
if check_username_isExist() == 0:#检查是否注册
print("The username is not exist,Please try again.")
else:
check_username_isLock()#检查是否锁定
wrong_times= check_password(wrong_times)#检查密码是否正确:错则累加wrong_times次数;对则成功登录
if wrong_times== 3:
write_lockusername()#达到三次进行锁定操作
exit()
----测试----
创建并预先写好username_password.txt:
创建好空的lock_username.txt文件:
测试未注册与已注册:
测试密码错误和被锁定
文件中出现被锁用户: