码迷,mamicode.com
首页 > 编程语言 > 详细

Python装饰器(4)

时间:2017-09-09 18:08:33      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:page   invalid   out   ldap   war   oca   功能   pre   home   

用装饰器完成:(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!

Python装饰器(4)

标签:page   invalid   out   ldap   war   oca   功能   pre   home   

原文地址:http://www.cnblogs.com/csy113/p/7498783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!