Day1-编写登录接口

需求:编写登录接口

  • 输入用户名密码
  • 认证成功后显示欢迎信息
  • 输错三次后锁定

流程图:

代码:

 1 # coding: utf-8
 2 # Version: python3.6.0
 3 # Tools: Pycharm 2018.2.2
 4 __date__ = '2018/9/6 22:20'
 5 __author__ = 'Bear_Cat'
 6 
 7 import sys
 8 
 9 retry_limit = 3
10 count = 0
11 account_file = 'D:/PycharmProjects/accounts.txt'
12 lock_file = 'D:/PycharmProjects/account_lock.txt'
13 
14 while count < retry_limit:  # 重复次数没超过3次,就不断循环
15 
16     userName = input('Please input your userName:')
17     # 输入用户名,打开account_lock.txt文件,检查该用户是否已经lock
18     with open(lock_file) as f1:
19         lock_contents = f1.readlines()
20 
21     for line in lock_contents:  # 遍历account_lock.txt文件
22         if userName == line.strip():  # 如果该用户已经被lock了,就直接退出while循环
23             sys.exit('User %s  has been locked!' % userName.title())
24 
25     passWord = input('Please input your passWord:')
26     # 输入密码,检查账号和密码是否匹配
27     with open(account_file) as f2:
28         account_contents = f2.readlines()
29 
30     match_flag = False  # 初始值为False,如果用户match成功了,就设置为True
31     for line in account_contents:
32         '''去掉每一行末尾的\n,并把这一行以空格为分隔符进行分割,
33            将分割出来的用户名和密码分别赋值给user和pwd两个变量
34         '''
35         user, pwd = line.strip().split()
36         if user == userName and pwd == passWord:  # 判断用户名和密码是否同时匹配
37             print(userName.title(), 'has match succeedly!')
38             match_flag = True
39             break  # 匹配成功就跳出for循环
40     if match_flag == False:
41         '''如果match_flag为False,表示上面的for循环中没有match上用户名和密码
42         '''
43         print('用户名或密码错误!')
44         count += 1  # 账号密码不匹配song计数器加1
45     else:
46         print('Welcome back!')
47         break  # 用户登录成功,打断while循环
48 else:
49     print('Your account has been locked!')
50     with open(lock_file, 'a') as  f:
51         f.write(userName + '\n')

测试结果:

C:\Users\uilliam\AppData\Local\Programs\Python\Python36-32\python.exe D:/PycharmProjects/python_learning/day1/day1.py
Please input your userName:eric
Please input your passWord:123456
Eric has match succeedly!
Welcome back!

Process finished with exit code 0
C:\Users\uilliam\AppData\Local\Programs\Python\Python36-32\python.exe D:/PycharmProjects/python_learning/day1/day1.py
Please input your userName:bill
Please input your passWord:123456
用户名或密码错误!
Please input your userName:bill
Please input your passWord:654321
用户名或密码错误!
Please input your userName:bill
Please input your passWord:abc123
用户名或密码错误!
Your account has been locked!

Process finished with exit code 0
C:\Users\uilliam\AppData\Local\Programs\Python\Python36-32\python.exe D:/PycharmProjects/python_learning/day1/day1.py
Please input your userName:bill
User Bill  has been locked!

Process finished with exit code 1

猜你喜欢

转载自www.cnblogs.com/bear-cat/p/9605685.html