Python使用裝飾器模擬用戶登陸驗證功能示例
本文實例講述了Python使用裝飾器模擬用戶登陸驗證功能。分享給大家供大家參考,具體如下:
# -*- coding:utf-8 -*- #!python3 user_list = [ {'name':'ad1','passwd':'123'}, {'name':'ad2','passwd':'123'}, {'name':'ad3','passwd':'123'}, {'name':'ad4','passwd':'123'} ] #初始狀態(tài),用來保存登陸的用戶, client_dic = {'username':None,'login':False} #添加新功能 def auth_func(func): def wrapper(*args,**kwargs): #參數(shù)檢查,判斷是否有用戶登錄,如果有,不用驗證,直接執(zhí)行函數(shù)的功能 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('用戶名或者密碼錯誤!') return wrapper @auth_func def index(): print("歡迎來到主頁") @auth_func def home(name): print("歡迎回家:%s"%name) @auth_func def shoppping_car(): print('購物車里有[%s,%s,%s]'%('奶茶','妹妹','娃娃')) print(client_dic) index() print(client_dic) home('root')
運行結(jié)果:
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python+tkinter實現(xiàn)網(wǎng)站下載工具
這篇文章主要為大家詳細介紹了如何利用Python+tkinter實現(xiàn)網(wǎng)站下載工具,實現(xiàn)所有數(shù)據(jù)一鍵獲取,文中的示例代碼講解詳細,感興趣的可以了解一下2023-03-03python基礎(chǔ)教程之簡單入門說明(變量和控制語言使用方法)
這篇文章主要介紹了開始學(xué)習(xí)python的第一步需要知道的知識(變量和控制語言使用方法),需要的朋友可以參考下2014-03-03使用Python3?Boto3包刪除AWS?CloudFormation的棧(Stacks)
這篇文章主要介紹了如何使用Python3?Boto3刪除AWS?CloudFormation的棧(Stacks),本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2024-01-01Numpy數(shù)組的轉(zhuǎn)置和軸交換的實現(xiàn)
本文主要介紹了Numpy數(shù)組的轉(zhuǎn)置和軸交換的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03