Python實現(xiàn)帶參數(shù)的用戶驗證功能裝飾器示例
本文實例講述了Python實現(xiàn)帶參數(shù)的用戶驗證功能裝飾器。分享給大家供大家參考,具體如下:
user_list = [
{'name': 'sb1', 'passwd': '123'},
{'name': 'sb2', 'passwd': '123'},
{'name': 'sb3', 'passwd': '123'},
{'name': 'sb4', 'passwd': '123'}
]
# 初始狀態(tài),用來保存登陸的用戶,
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':
# 參數(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('用戶名或者密碼錯誤!')
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('購物車?yán)镉衃%s,%s,%s]' % ('奶茶', '妹妹', '娃娃'))
print(client_dic)
index()
print(client_dic)
home('root')
運行結(jié)果:
{'username': None, 'login': False}
filedb
一臉蒙蔽的驗證方式
歡迎來到主頁
{'username': None, 'login': False}
user
一臉蒙蔽的驗證方式
歡迎回家:root
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
解決Python設(shè)置函數(shù)調(diào)用超時,進程卡住的問題
今天小編就為大家分享一篇解決Python設(shè)置函數(shù)調(diào)用超時,進程卡住的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
Python 數(shù)據(jù)結(jié)構(gòu)之隊列的實現(xiàn)
這篇文章主要介紹了Python 數(shù)據(jù)結(jié)構(gòu)之隊列的實現(xiàn)的相關(guān)資料,需要的朋友可以參考下2017-01-01
python直接調(diào)用和使用swig法方調(diào)用c++庫
這篇文章主要介紹了python直接調(diào)用和使用swig法方調(diào)用c++庫,c++運算速度快于python,python簡單易寫。很多時候?qū)τ谝延械腸++代碼也不想用python重寫,此時就自然而然地想到用python調(diào)用c或者c++,兩全其美,需要的朋友可以參考一下2022-03-03
完美解決Pycharm中matplotlib畫圖中文亂碼問題
這篇文章主要介紹了完美解決Pycharm中matplotlib畫圖中文亂碼問題,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01

