Python學習之路:裝飾器實現終極版
阿新 • • 發佈:2017-11-28
index type after color return 結果 python turn 調用
網站實現驗證功能裝飾器:
import time user,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 wrapper def index(): print("welcome to index page") @auth def home(): print("welcome to home page ") return "from home" @auth def bbs(): print("welcome to bbs page") index() home() print(home())#執行結果為空,調用home相當於調用wraper bbs()
保留要裝飾函數的返回結果:
import time user,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 wrapper def index(): print("welcome to index page") @auth def home(): print("welcome to home page ") return "from home" @auth def bbs(): print("welcome to bbs page") index() home() print(home())#執行結果為空,調用home相當於調用wraper bbs()
不同網頁不同驗證方式的裝飾器:
import time user,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的輸出結果 return res else: exit("\033[31;1mInvalid username or password\033[0m") elif auth_type=="ldap": print("搞毛線ldap,不會。。。。") return wrapper return outer_auth def index(): print("welcome to index page") @auth(auth_type="local") def home(): print("welcome to home page ") return "from home" @auth(auth_type="ldap") def bbs(): print("welcome to bbs page") index() home() print(home())#執行結果為空,調用home相當於調用wraper bbs()
Python學習之路:裝飾器實現終極版