【每日一练】装饰器

写一个用户登录认证函数,要求:

1.要求用户输入账号密码和txt中的用户名数据库对比;

2.要求用户有三次尝试机会;

3.要求用户登陆后,执行其他功能无需再验证;

4.要求拥有超时重新登录功能;

txt数据:

{'auth_name':'user0', 'auth_passwd':'123'}
{'auth_name':'user1', 'auth_passwd':'123'}
{'auth_name':'user2', 'auth_passwd':'123'}
{'auth_name':'user3', 'auth_passwd':'123'}
 1 import time
 2 
 3 current_state = {'user': None, 'login': False}
 4 count = 3
 5 start = 0
 6 end = 0
 7 
 8 
 9 def login(fun):
10     global count
11     global start
12     while count > 0:
13         user_name = input('enter your user name:\n')
14         passwd = input('enter your user password:\n')
15         with open('test', 'r') as f:
16             for item in f:
17                 item = eval(item)
18                 if item['name'] == user_name and item['passwd'] == passwd:
19                     print('login success.')
20                     current_state['user'] = user_name
21                     current_state['login'] = True
22                     res = fun()
23                     start = time.time()
24                     return res
25             else:
26                 count -= 1
27                 print('the user name or password is wrong ,you have %d times.' % count)
28                 continue
29     else:
30         print('three times failed, please try later.')
31 
32 
33 def auth(fun):
34     def user_auth(*args, **kwargs):
35         global end
36         global start
37         global count
38         if end - start < 2:
39             if current_state['user'] and current_state['login']:
40                 res = fun(*args, **kwargs)
41                 end = time.time()
42                 return res
43             else:
44                 login(fun)
45         else:
46             start = 0
47             end = 0
48             count = 3
49             current_state['user'] = None
50             current_state['login'] = False
51             print('time out ,login again.')
52             login(fun)
53     return user_auth
54 
55 
56 @auth
57 def log():
58     print('welcome logging %s.' % current_state['user'])
59 
60 
61 @auth
62 def home():
63     time.sleep(2)
64     print('welcome to home index.')
65 
66 
67 @auth
68 def shoping_car():
69     time.sleep(2)
70     print('welcome to shopping car.')
71 
72 
73 log()
74 home()
75 shoping_car()
View Code

 

 
 
 
 
posted @ 2018-09-28 23:47  木石溪  阅读(131)  评论(0编辑  收藏  举报