十一.Python_函式閉包模擬Session
阿新 • • 發佈:2018-12-23
Python_函式閉包模擬Session
# 19.函式閉包模擬Session #模擬資料庫 list_user=[{"name":"tom","password":"123"}, {"name": "cat", "password": "123"}, {"name": "ssh", "password": "123"}, {"name": "alex", "password": "123"}, {"name": "marry", "password": "123"}, {"name": "sam", "password": "123"}] #模擬資料庫的使用者 #模擬Session curren_login={"name":None,"status":False} #當前登入狀態 #判斷使用者登陸驗證的裝飾器 def validate(con): #獲取@validator()的引數 def _validate(func): #獲取目標函式 def wrapper(): #獲取目標函式的引數 if(curren_login["name"] and curren_login["status"]): #獲取當前登入狀態是否存在使用者登入 res = func(curren_login["name"]) #使用者登入呼叫目標函式 return res #返回目標函式 print("歡迎來到京東商城!") name=input("請輸入使用者名稱:") #使用者沒用登陸讓使用者輸入使用者名稱 password=input("請輸入密碼:") #使用者沒用登陸讓使用者輸入使用者密碼 for i in list_user: #迴圈資料庫的使用者 if i["name"]==name: #判斷該使用者是否存在資料庫中 if(password==i["password"]): #判斷該使用者的密碼與資料庫儲存的密碼是否一致 print("執行%s函式"%con) #輸出要執行的函式 res=func(name) #使用者登入成功呼叫目標函式 curren_login["name"]=name #設定登入狀態的使用者 curren_login["status"]=True #設定登入狀態 return res #返回目標函式 else: #使用者名稱或密碼輸入有誤 print("您輸入的使用者名稱或密碼有誤!") #列印登陸失敗的結果 return wrapper #將wrapper函式作為返回值 return _validate #將_validate函式作為返回值 #跳轉jd首頁 @validate("index") #相當於index=_validator(index) def index(name="1223"): print("%s!歡迎來到JD頁面!"%name) #跳轉jd個人主頁 @validate("home") #相當於home=_validator(home) def home(name="1223"): print("歡迎%s來到home!"%name) #跳轉jd購物車 @validate("shop") #相當於shop=_validator(shop) def shop(name="1223"): print("%s 購物車裡有 零食 數碼產品"%name) index() #呼叫index函式 # home() # shop()