Python使用裝飾器模擬用戶登陸驗證功能示例
更新時間:2018年08月24日 08:41:04 作者:我是馬克思小清新
這篇文章主要介紹了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')
運行結果:
更多關于Python相關內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結構與算法教程》、《Python編碼操作技巧總結》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python+tkinter實現(xiàn)網(wǎng)站下載工具
這篇文章主要為大家詳細介紹了如何利用Python+tkinter實現(xiàn)網(wǎng)站下載工具,實現(xiàn)所有數(shù)據(jù)一鍵獲取,文中的示例代碼講解詳細,感興趣的可以了解一下2023-03-03python基礎教程之簡單入門說明(變量和控制語言使用方法)
這篇文章主要介紹了開始學習python的第一步需要知道的知識(變量和控制語言使用方法),需要的朋友可以參考下2014-03-03使用Python3?Boto3包刪除AWS?CloudFormation的棧(Stacks)
這篇文章主要介紹了如何使用Python3?Boto3刪除AWS?CloudFormation的棧(Stacks),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2024-01-01