Web site Implementation validation feature decorator:
Import timeuser,passwd= ' Alex ', ' abc123 ' def Auth (func): def wrapper (*args,**kwargs): print ("Wraper func args: ", *args,**kwargs) username=input (" Username: "). Strip () password=input (" Password: "). Strip () if user== Username and Passwd==password: print ("\033[32;1muser has passed authentication\033[0m") func (*args,**kwargs # #print ("---after authentication---") #保留要装饰函数home的输出结果 #return res else: exit ("\033[31; 1mInvalid username or password\033[0m ") return Wrapperdef index (): print (" Welcome to Index page ") @authdef Home (): print ("Welcome to Home Page") return ' from home ' @authdef BBS (): print ("Welcome to BBS page") Index () Home () print (Home ()) #执行结果为空, calling home is equivalent to calling Wraperbbs ()
Leave the returned result of the function to be decorated:
Import timeuser,passwd= ' Alex ', ' abc123 ' def Auth (func): def wrapper (*args,**kwargs): print ("Wraper func args: ", *args,**kwargs) username=input (" Username: "). Strip () password=input (" Password: "). Strip () if user== Username and Passwd==password: print ("\033[32;1muser has passed authentication\033[0m") Res=func (*args,** Kwargs) # print ("---after authentication---") #保留要装饰函数home的输出结果 return res else: exit ("\033[31; 1mInvalid username or password\033[0m ") return Wrapperdef index (): print (" Welcome to Index page ") @authdef Home (): print ("Welcome to Home Page") return ' from home ' @authdef BBS (): print ("Welcome to BBS page") Index () Home () print (Home ()) #执行结果为空, calling home is equivalent to calling Wraperbbs ()
Decorators with different authentication methods for different Web pages:
Import timeuser,passwd= ' Alex ', ' abc123 ' def auth (auth_type): Print ("auth func:", Auth_type) def Outer_auth (func): def wrapper (*args,**kwargs): Print ("Wraper func args:", *args,**kwargs) if auth_type== "local": Username=input ("Username:"). Strip () Password=input ("Password:"). Strip () if user== Username and Passwd==password:print ("\033[32;1muser has passed authentication\033[0m") Res=func (*args,**kwargs) # print ("---after authentication---") #保留要装饰函数home的输出结果 r Eturn Res else:exit ("\033[31;1minvalid username or password\033[0m") elif au th_type== "LDAP": Print ("Engage the yarn LDAP, will not ....") ") return wrapper return Outer_authdef index (): Print (" Welcome to Index page ") @auth (auth_type=" local ") def Hom E (): Print ("Welcome to Home Page") return "from Home" @auth (auth_type= "LDAP") def BBS (): Print ("Welcome to BBS Page") Index () home () print (Home ()) #执行结果为空, call home equivalent to call Wraperbbs ()
Python Learning Path: adorners for the Ultimate edition