本文實例講述了Python實現帶參數的用戶驗證功能裝飾器。分享給大家供大家參考,具體如下:
user_list = [ {'name': 'sb1', 'passwd': '123'}, {'name': 'sb2', 'passwd': '123'}, {'name': 'sb3', 'passwd': '123'}, {'name': 'sb4', 'passwd': '123'}]# 初始狀態,用來保存登陸的用戶,client_dic = {'username': None, 'login': False}# 添加新功能def auth(auth_type='filedb'): def auth_func(func): def wrapper(*args, **kwargs): print(auth_type) if auth_type == 'fildb': # 參數檢查,判斷是否有用戶登錄,如果有,不用驗證,直接執行函數的功能 if client_dic['username'] and client_dic['login']: res = func(*args, **kwargs) return res # 輸入用戶名和密碼 username = input('用戶名:').strip() passwd = input('passwd:').strip() # 對比列表,檢查用戶名和密碼是否正確 for user_dic in user_list: if username == user_dic['name'] and passwd == user_dic['passwd']: client_dic['username'] = user_dic['name'] client_dic['login'] = True res = func(*args, **kwargs) return res else: print('用戶名或者密碼錯誤!') elif auth_type == 'pass': print('不知道什么驗證方式') res = func(*args, **kwargs) return res else: print('一臉蒙蔽的驗證方式') res = func(*args, **kwargs) return res return wrapper return auth_func@auth(auth_type='filedb')def index(): print("歡迎來到主頁")@auth(auth_type='user')def home(name): print("歡迎回家:%s" % name)@auth(auth_type='pass')def shoppping_car(): print('購物車里有[%s,%s,%s]' % ('奶茶', '妹妹', '娃娃'))print(client_dic)index()print(client_dic)home('root')運行結果:
{'username': None, 'login': False}
filedb
一臉蒙蔽的驗證方式
歡迎來到主頁
{'username': None, 'login': False}
user
一臉蒙蔽的驗證方式
歡迎回家:root
更多關于Python相關內容可查看本站專題:《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答