基于Python 3.x
应用场景:
现在有很多网站
需要统一添加验证功能,但是又不能修改原网站代码,与网站调用方式,需要引入装饰器功能:
需求:
给不同的网页添加装饰器 要求home()采用本地验证 要求bbs()采用ldap验证 要求用户输入账号密码,如果账号错误三次会被锁定
Username_list :
Iriving 123456 alex 123456 questhaha qwer 代码如下:
1 user = 'Iriving' 2 passwd = '123456' 3 4 def Judge_User(): 5 enter_times = 0 6 while(enter_times <= 3) : 7 username = input('Please enter your username:').strip() 8 password = input('Please enter your password:').strip() 9 if user == username and passwd == password:10 # \033[31;1m%s\033[0m11 print("\033[31;1mLogin Success..... ")12 break13 elif user == username and passwd != password:14 print("\033[34;1mYour passwd is not true,please try it again\033[0m")15 # enter_times += 116 continue17 else:18 print("\033[34;1mYour username is not true,please try it again\033[0m")19 enter_times += 120 continue21 else:22 f1 = open('lock_list','w+',encoding='utf-8')23 f1.write(username)24 exit('\033[33;1m\nYour enter times is enough\033[0m')25 26 def auth(auth_type):27 def out_wrapper(func):28 def wrapper(*args,**kwargs):29 # enter_times = 0 # 定义一个局部变量来计算输入次数30 if auth_type == 'local verification':31 Judge_User()32 func(*args,**kwargs)33 if auth_type == 'ldap verification':34 Judge_User()35 func(*args,**kwargs)36 return wrapper37 return out_wrapper38 39 def index():40 print("Welcome to the index page")41 42 @auth(auth_type='local verification')43 def home():44 print("Welcome to the home page")45 46 @auth(auth_type='ldap verification')47 def bbs():48 print("Welcome to the bbs page")49 50 @auth(auth_type = 'local verification')51 def return_page():52 return 'Hello~'53 54 index()55 home()56 bbs()57 return_page()