装饰器应用之登录
模拟电商网站登录场景,执行特定操作时都需要用户是登录状态
# date:2019/04/23
# _author :taozi
# 装饰器应用之模拟登录(伪代码)
username = 'taozi'
password = '123456'
login_state = False
def auth(authType='jingdong'):
def login(f):
def inner():
global login_state
if login_state is False:
username_i = input("username:")
password_i = input("password:")
if authType == 'jingdong':
print('jingdong login...')
if username_i == username and password_i == password:
print("login succeed ! Welcome to JD!")
login_state = True
f()
else:
print("login failure ")
elif authType == 'weixin':
print('weixin login....')
if username_i == username and password_i == password:
print("login succeed ! Welcome to JD!")
login_state = True
f()
else:
print("login failure ")
else:
print('authtype is wrong')
else:
print("you are already logged in ")
f()
return inner
return login
# home\finance\book 三个页面都需要登录
@auth('jingdong')
def home():
print('Welcome home page')
@auth('weixin')
def finance():
print('Welcome finace page')
@auth()
def book():
print('Welcom book')
# 调用操作函数
home()
finance()
book()