登录作业——使用装饰器

#_*_coding:utf-8_*_
#作者:王佃元
#日期:2019/12/25
'''
需求
1.使用文件保存用户名及密码
2.程序启动后可以看到三个页面
3.用户选择任一界面可进入,如果没有登录,提示用户输入

1:京东 home page 只能使用京东的登录
2:金融 finance page 只能使用微信登录
3:书籍 book page 两种皆可以

不同的登录页面调用同一个登录方法
打印登录页面
用户选择要登录的页面,如果是1则调用'home page'、如果是2则调用'finance page'(循环打印pages列表,获取用户输入,根据用户输入调用方法)
登录之后进行页面切换无需再次登录(页面切换首先进行是否登录验证,如果已登录,则显示切换页面,否则提示登录)
装饰器:
1.为什么装饰器要传函数进来,因为装饰器是对函数功能的扩展,所以要传函数进来并执行
2.为什么要返回装饰器内嵌函数,因为不返回内嵌函数无法进行内嵌函数的执行
'''

# print('welcome to jingdong!')
pages = ['home page', 'finance page', 'book page']
login_status = False


def login_decorator(login):
def login_page(*args):
global login_status
for page in pages:
print('%d:' % (pages.index(page) + 1), page)
args = input('please enter the choice:')
if args and args.isdigit():
user_select = int(args)
if user_select in range(1, len(pages) + 1) and login_status:
login(user_select)
elif user_select not in range(1, len(pages) + 1):
print('please enter the right number')
else:
while True:
username = input('please enter the username:')
password = input('please enter the password:')
with open('jingdong', 'r') as jingdong:
jingdong_login = eval(jingdong.read().strip())
with open('weixin', 'r') as weixin:
weixin_login = eval(weixin.read().strip())
if user_select == 1 and username in jingdong_login and password == jingdong_login[username]:
login(user_select)
login_status = True
break
elif user_select == 2 and username in weixin_login and password == weixin_login[username]:
login(user_select)
login_status = True
break
else:
print('username or password wrong ,please enter again')
elif args.strip().lower() == 'q':
exit('welcome back again')
else:
print('please enter the number , not a character')
return login_page


@login_decorator
def login(user_select):
print('welcome to %s' % pages[user_select-1])


while True:
login()
# for page in pages:
# print('%d:' % (pages.index(page)+1), page)
# user_select = input('please enter the choice:')
# if user_select.isdigit():
# user_select = int(user_select)
# if user_select in range(1, len(pages)+1) and login_status:
# print('welcome to %s' % pages[user_select - 1])
# elif user_select not in range(1, len(pages)+1):
# print('please enter the right number')
# else:
# while True:
# username = input('please enter the username:')
# password = input('please enter the password:')
# if username == 'dery' and password == 'wong':
# print('welcome to %s' % pages[user_select - 1])
# login_status = True
# break
# else:
# print('username or password wrong ,please enter again')
# elif user_select == 'q':
# exit('welcome back again')
# else:
# print('please enter the number , not a character')



你可能感兴趣的:(登录作业——使用装饰器)