# Author: 刘佳赐-Isabelle
# Email: jiaci.liu@gmail.com
'''
练习题:
1、整理装饰器的形成过程,背诵装饰器的固定格式
2、编写装饰器,在每次执行被装饰函数之前打印一句’每次执行被装饰函数之前都得先经过这里,这里根据需求添加代码’
3、编写装饰器,在每次执行被装饰函数之后打印一句’每次执行完被装饰函数之后都得先经过这里,这里根据需求添加代码’
4、编写装饰器,在每次执行被装饰函数之前让用户输入用户名,密码,给用户三次机会,登录成功之后,才能访问该函数.
5、编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件,只支持单用户的账号密码,给用户三次机会),要求登录成功一次,后续的函数都无需再输入用户名和密码
6、编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件,可支持多账号密码),要求登录成功一次(给三次机会),后续的函数都无需再输入用户名和密码。
7、给每个函数写一个记录日志的功能,
'''
'''
1、整理装饰器的形成过程,背诵装饰器的固定格式
'''
# def wrapper(f):
# def inner(*args, **kwargs):
# ret = f(*args, **kwargs)
# return ret
# return inner
'''
2、编写装饰器,在每次执行被装饰函数之前打印一句’每次执行被装饰函数之前都得先经过这里,这里根据需求添加代码’
'''
# def wrapper2(f):
# def inner2(*args, **kwargs):
# print('每次执行被装饰函数之前都得先经过这里,这里根据需求添加代码')
# ret = f(*args, **kwargs)
# return ret
# return inner2
'''
3、编写装饰器,在每次执行被装饰函数之后打印一句’每次执行完被装饰函数之后都得先经过这里,这里根据需求添加代码’
'''
# def wrapper3(f):
# def inner(*args, **kwargs):
# ret = f(*args, **kwargs)
# print('每次执行完被装饰函数之后都得先经过这里,这里根据需求添加代码')
# return ret
# return inner
'''
4、编写装饰器,在每次执行被装饰函数之前让用户输入用户名,密码,给用户三次机会,登录成功之后,才能访问该函数.
'''
# # Method 1
# def wrapper41(f):
# def inner(*args, **kwargs):
# '''
# Function to check user name and password
# :param args:
# :param kwargs:
# :return:
# '''
# userinfo = []
# username_list = []
# with open('jd_userinfo', encoding='utf-8') as file:
# for line in file:
# username_list.append(line.strip().split('|')[0])
# userinfo.append(line.strip().split('|'))
#
# username = input('Please input your username:').strip()
#
# if username in username_list:
# password = input('Please input your password:').strip()
# for times in range(0, 3):
# if [username, password] in userinfo and times < 2:
# ret = f(*args, **kwargs)
# return ret
# elif [username, password] not in userinfo and times < 2:
# times += 1
# print('Invalid Password, left %d times!' % (3-times))
# password =input('Please input your password again:').strip()
# elif [username, password] not in userinfo and times >= 2:
# print('Invalid Password, tried 3 times, your account has been locked!!')
# elif username not in username_list:
# print('Invalid username!')
# return inner
#
# # Method 2
# def wrapper42(f):
# def inner(*args, **kwargs):
# times = 0 # tried times
# userinfo = []
# username_list = []
# with open('jd_userinfo', encoding='utf-8') as file:
# for line in file:
# username_list.append(line.strip().split('|')[0])
# userinfo.append(line.strip().split('|'))
#
# username = input('Please input your username:').strip()
#
# if username in username_list:
# password = input('Please input your password:').strip()
# while 1:
# if [username, password] in userinfo and times < 2:
# ret = f(*args, **kwargs)
# return ret
# elif [username, password] not in userinfo and times < 2:
# times += 1
# print('Invalid Password, left %d times!' % (3-times))
# password =input('Please input your password again:').strip()
# elif [username, password] not in userinfo and times >= 2:
# print('Invalid Password, tried 3 times, your account has been locked!!')
# break
#
# elif username not in username_list:
# print('Invalid username!')
# return inner
#
# @wrapper41
# # @wrapper42
# def f():
# print(111)
#
# f()
'''
5、编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件,只支持单用户的账号密码,给用户三次机会),
要求登录成功一次,后续的函数都无需再输入用户名和密码
'''
# login_status = {
# 'username': None,
# 'status': False,
# }
#
# def wrapper(f):
# def inner(*args, **kwargs):
# '''
# Function to check login status, if not logged in, check user name and password to login;
# once logged in, no need to verify status for further functions!
# :param args:
# :param kwargs:
# :return:
# '''
# if login_status['status']:
# ret = f(*args, **kwargs)
# return ret
# else:
# userinfo = []
# username_list = []
# with open('jd_userinfo', encoding='utf-8') as file:
# for line in file:
# username_list.append(line.strip().split('|')[0])
# userinfo.append(line.strip().split('|'))
#
# username = input('Please input your username:').strip()
#
# if username in username_list:
# password = input('Please input your password:').strip()
# for times in range(0, 3):
# if [username, password] in userinfo and times < 2:
# ret = f(*args, **kwargs)
# login_status['status'] = True
# login_status['username'] = username
# return ret
# elif [username, password] not in userinfo and times < 2:
# times += 1
# print('Invalid Password, left %d times!' % (3-times))
# password =input('Please input your password again:').strip()
# elif [username, password] not in userinfo and times >= 2:
# print('Invalid Password, tried 3 times, your account has been locked!!')
# elif username not in username_list:
# print('Invalid username!')
# return inner
#
# @wrapper
# def func1():
# print(111)
#
# @wrapper
# def func2():
# print(222)
#
# @wrapper
# def func3():
# print(333)
#
# func1()
# func2()
# func3()
'''
6、编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件,可支持多账号密码),
要求登录成功一次(给三次机会),后续的函数都无需再输入用户名和密码。
'''
# login_status = {
# 'TM_username': None,
# 'TM_status': False,
# 'JD_username': None,
# 'JD_status': False,
# }
#
#
# def account(Flag):
# def wrapper(f):
# def inner(*args, **kwargs):
# '''
# Function to check login status, if not logged in (available to check multiple accounts),
# check user name and password to login;
# once logged in, no need to verify status for further functions!
# :param args:
# :param kwargs:
# :return:
# '''
# account_book = Flag.lower()+'_userinfo'
# account_username = Flag+'_username'
# account_status = Flag+'_status'
#
# if login_status[account_status]:
# ret = f(*args, **kwargs)
# return ret
# else:
# userinfo = []
# username_list = []
#
# with open(account_book, encoding='utf-8') as file:
# for line in file:
# username_list.append(line.strip().split('|')[0])
# userinfo.append(line.strip().split('|'))
#
# username = input('Please input your %s account username:' % Flag).strip()
#
# if username in username_list:
# password = input('Please input your %s account password:' % Flag).strip()
# for times in range(0, 3):
# if [username, password] in userinfo and times < 2:
# login_status[account_status] = True
# login_status[account_username] = username
# ret = f(*args, **kwargs)
# return ret
# elif [username, password] not in userinfo and times < 2:
# times += 1
# print('Invalid Password, left %d times!' % (3-times))
# password =input('Please input your password again:').strip()
# elif [username, password] not in userinfo and times >= 2:
# print('Invalid Password, tried 3 times, your account has been locked!!')
# elif username not in username_list:
# print('Invalid username!')
# return inner
# return wrapper
#
# @account('TM')
# def func1():
# print(111)
#
# @account('JD')
# def func2():
# print(222)
# print(login_status['JD'+'_username'])
#
# @account('TM')
# def func3():
# print(333)
#
# func1()
# func2()
# func3()
'''
7、给每个函数写一个记录日志的功能,
'''
# import time
# struct_time = time.localtime()
#
# def wrapper(f):
# def inner(*args, **kwargs):
# ret = f(*args, **kwargs)
# with open('diary', mode='a', encoding='utf-8') as file:
# file.write('Function {} was conducted at {}'.format(str(f)[10:str(f).index('at')-1],
# time.strftime("%Y-%m-%d %H:%M:%S", struct_time)))
# return ret
# return inner
#
# @wrapper
# def func():
# print(1)
#
# func()
"""
功能要求:每一次调用函数之前,要将函数名称,时间节点记录到log的日志中。
所需模块:
import time
struct_time = time.localtime()
print(time.strftime("%Y-%m-%d %H:%M:%S",struct_time))
1),启动程序,首页面应该显示成如下格式:
欢迎来到博客园首页
1:请登录
2:请注册
3:文章页面
4:日记页面
5:评论页面
6:收藏页面
7:注销
8:退出程序
2),用户输入选项,3~6选项必须在用户登录成功之后,才能访问成功。
3),用户选择登录,用户名密码从register文件中读取验证,三次机会,
没成功则结束整个程序运行,成功之后,可以选择访问3~6项,访问页面之前,
必须要在log文件中打印日志,日志格式为-->用户:xx 在xx年xx月xx日 执行了 %s函数,
访问页面时,页面内容为:欢迎xx用户访问评论(文章,日记,收藏)页面
4),如果用户没有注册,则可以选择注册,注册成功之后,可以自动完成登录,然后进入首页选择。
5),注销用户是指注销用户的登录状态,使其在访问任何页面时,必须重新登录。
"""
# import time
# struct_time = time.localtime()
#
#
# login_status = {
# 'TM_username': None,
# 'TM_status': False,
# 'JD_username': None,
# 'JD_status': False,
# }
#
# default_page = '''
# 欢迎来到博客园首页
# 1:请登录
# 2:请注册
# 3:文章页面
# 4:日记页面
# 5:评论页面
# 6:收藏页面
# 7:注销
# 8:退出程序
# '''
# def account(Flag='TM'):
# def login_check(func):
# '''
# Decoration function
# :param func: function to be decorated
# :return: func
# '''
# def inner(*args, **kwargs):
# '''
# decoration function
# :param args:
# :param kwargs:
# :return: decorated function
# '''
# account_book = Flag.lower()+'_userinfo'
# account_username = Flag+'_username'
# account_status = Flag+'_status'
# account_diary = Flag+'_diary'
#
# if login_status[account_status]:
# ret = func(*args, **kwargs)
#
# with open(account_diary, mode='a', encoding='utf-8') as file:
# file.write('用户:{}在{}执行了{}\n'.format(login_status[account_username],
# time.strftime("%Y-%m-%d %H:%M:%S", struct_time),
# str(func)[10:str(func).index('at') - 1]))
# return ret
# else:
# print("Please login first!")
#
# # check user name and password
# username = input("Please input your username:").strip()
#
# # make a list of saved username and corresponding password
# # TODO: is this necessary to create a new list?
# username_list = [] # list of user name
# userinfo_list = [] # list of user name and corresponding password
# with open(account_book, encoding="utf-8") as file:
# for line in file:
# username_list.append(line.strip().split("|")[0]) # TODO:any simpler expression?
# userinfo_list.append(line.strip().split("|")) # TODO:any simpler expression?
# if username in username_list:
# password = input('Please input your password:').strip()
# for times in range(0, 3):
# if [username, password] in userinfo_list:
# login_status[account_username] = username
# login_status[account_status] = True
# ret = func(*args, **kwargs)
#
# with open(account_diary, mode='a', encoding='utf-8') as file:
# file.write('用户:{}在{}执行了{}\n'.format(login_status[account_username],
# time.strftime("%Y-%m-%d %H:%M:%S", struct_time),
# str(func)[10:str(func).index('at') - 1]))
# return ret
# elif [username, password] not in userinfo_list and times < 2:
# times += 1
# print('Invalid password, left %d times!' % (3 - times))
# password = input('Please input your password again:')
# elif [username, password] not in userinfo_list and times >= 2:
# print('Invalid password, failed for three times!! You account has been locked!')
# elif username not in username_list:
# print("Unregistered username, please register!")
# register()
# return inner
# return login_check
#
#
# @account('JD')
# def register():
# global operation
#
# # check whether the username is available (occupied or not)
# username_check = [] # TODO: is this necessary to create a new list?
#
# with open("jd_userinfo", "r+", encoding="utf-8") as file:
# for line in file:
# username_check.append(line.strip().split()[0])
# username = input("Please set your username:").strip()
# while 1:
# if username not in username_check:
# password = input("Please set your password:")
# file.write("{}|{}\n".format(username, password))
#
# login_status['JD'+'_status'] = True
# login_status['JD'+'_username'] = username
# print(default_page)
#
# with open('JD' + '_diary', mode='a', encoding='utf-8') as file2:
# file2.write('用户:{}在{}执行了{}\n'.format(login_status['JD' + '_username'],
# time.strftime("%Y-%m-%d %H:%M:%S", struct_time),
# str(register)[10:str(register).index('at') - 1]))
# operation = input('Please select your operation(1-8):')
# dic[int(operation)]()
#
# elif username in username_check:
# print("Username has been taken, please reset your username!!")
# username = input("Please set your username again:").strip()
#
# @account('JD')
# def login():
# print(default_page)
# operation = int(input('Please select your operation(1-8):'))
# if operation == 1:
# print('You have already logged in!!')
# operation = int(input('Please select your operation(2-8):'))
# else:
# dic[operation]()
#
#
# @account('JD')
# def page():
# print("欢迎用户%s访问文章页面" % login_status['JD'+'_username'])
# operation = int(input('Please select your operation(1-8):'))
# dic[operation]()
#
# @account('JD')
# def diary():
# print("欢迎用户%s访问日志页面" % login_status['JD'+'_username'])
# with open('JD'+'_diary', encoding='utf-8') as file:
# for line in file:
# print(line.strip('\n'))
# operation = int(input('Please select your operation(1-8):'))
# dic[operation]()
#
# @account('JD')
# def comment():
# print("欢迎用户%s访问评论页面" % login_status['JD'+'_username'])
# operation = int(input('Please select your operation(1-8):'))
# dic[operation]()
#
# @account('JD')
# def save():
# print("欢迎用户%s访问收藏页面" % login_status['JD'+'_username'])
# operation = int(input('Please select your operation(1-8):'))
# dic[operation]()
#
# @account('JD')
# def logout():
# print("账号已退出!")
#
# @account('JD')
# def quit_operation():
# pass
#
# dic = {
# 1: login,
# 2: register,
# 3: page,
# 4: diary,
# 5: comment,
# 6: save,
# 7: logout,
# 8: quit_operation,
# }
#
#
# if __name__ == '__main__':
# print(default_page)
# operation = int(input('Please select your operation(1-8):'))
# dic[operation]()