最近看了下Python宰译,的確是一種語(yǔ)義簡(jiǎn)潔,且特別適合快速開(kāi)發(fā)的語(yǔ)言,學(xué)習(xí)了這個(gè)語(yǔ)言的裝飾器模式,想記錄下自己的一點(diǎn)點(diǎn)感想:
虛擬業(yè)務(wù)場(chǎng)景: 假設(shè)有三個(gè)頁(yè)面:home,finance砾赔,book三個(gè)函數(shù),分別使用京東帳號(hào)青灼,微信帳號(hào)暴心,和普通帳號(hào)登錄,現(xiàn)在三個(gè)頁(yè)面已經(jīng)正式上線使用杂拨,要求不修改調(diào)用代碼的情況下专普,使用裝飾器模式來(lái)為三個(gè)函數(shù)添加登錄驗(yàn)證:
具體的代碼塊如下:
#__author: "hong liu"
#date: 2018-03-08
import json
login_status =False
# 把驗(yàn)證信息組裝為字典
def analy_file(properties):
user_info = {}
if type(properties) ==list:
for linein properties:
if '=' in line:
platform,user_json = line.split('=')
platform = platform.strip()
user_json = json.loads(user_json.strip())
user_info[platform] = user_json
return user_info
# 通過(guò)裝飾器模式來(lái)實(shí)現(xiàn)不修改工程代碼的情況下添加登錄驗(yàn)證
def auth(auth_type =''):
def login(func):
def inner(user_info):
if login_status ==False:
if auth_type =='jingdong':#驗(yàn)證類(lèi)型為京東帳號(hào)
? ? ? ? ? ? ? ? ? ? user_name =input('jingdong username:')
pass_word =input('jingdong password:')
if user_info['jingdong']['user_name'] == user_nameand user_info['jingdong']['pass_word'] == pass_word:
func()
else:
print('login jingdong fail')
if auth_type =='weixin':#驗(yàn)證類(lèi)型為微信帳號(hào)
? ? ? ? ? ? ? ? ? ? user_name =input('weixin username:')
pass_word =input('weixin password:')
if user_info['weixin']['user_name'] == user_nameand user_info['weixin']['pass_word'] == pass_word:
func()
else:
print('login weixin fail')
if auth_type =='':#普通帳號(hào)驗(yàn)證
? ? ? ? ? ? ? ? ? ? user_name =input('username:')
pass_word =input('password:')
if user_info['customer']['user_name'] == user_nameand user_info['customer']['pass_word'] == pass_word:
func()
else:
print('login fail')
return inner
return login
#主頁(yè)面,使用京東帳號(hào)登錄
@auth(auth_type ='jingdong')
def home():
print('welcome to home page')
#財(cái)務(wù)專(zhuān)欄弹沽,使用微信帳號(hào)登錄
@auth(auth_type ='weixin')
def finance():
print('welcome to finance page')
#書(shū)本頁(yè)面檀夹,使用普通帳號(hào)登錄
@auth(auth_type ='')
def book():
print('welcome to book page')
file_info = []
# 從文件中讀取用戶(hù)登錄驗(yàn)證信息
with open('./user_info.txt','r',encoding='UTF-8')as f:
for linein f:
file_info.append(line.strip('\n'))
user_info = analy_file(file_info)
home(user_info) #最后調(diào)用home(user_info)會(huì)發(fā)現(xiàn)需要驗(yàn)證了