用装饰器完成:(1)index登录不需认证、home和bbs 登录需要认证功能;(2)home登录用本地认证,bbs登录用ldap认证

 1 __author__ = "csy"
 2 import time
 3 
 4 user,passwd = 'csy','123456'
 5 
 6 def auth(auth_type):            #最外层auth用于传递auth_type认证类型
 7     print("auth func",auth_type)
 8     def outer_wrapper(func):
 9         def wrapper(*args, **kwargs):
10             print("wrapper func args", *args,**kwargs)
11             if auth_type == 'local':
12                 username = input("Username:").strip()
13                 password = input("Password:").strip()
14 
15                 if user == username and passwd == password:
16                     print("\033[32;1mUser has passed authentication")
17                     res = func(*args, **kwargs)
18                     return res
19                 else:
20                     exit("\033[31;1mInvalid username or password\033[0m")
21             elif auth_type == 'ldap':
22                 print("hehe")
23         return wrapper
24     return outer_wrapper
25 
26 def index():
27     print("welcome to index page!")
28 @auth(auth_type='local')
29 def home():
30     print("welcome to home page!")
31 @auth(auth_type='ldap')
32 def bbs():
33     print("welcome to bbs page!")
34 
35 
36 home()
37 bbs()
38 index()

输出结果:

auth func local
auth func ldap
wrapper func args
Username:csy      #输入
Password:123456      #输入
User has passed authentication
welcome to home page!
wrapper func args
hehe
welcome to index page!

posted on 2017-09-09 17:30  csy113  阅读(108)  评论(0编辑  收藏  举报