# 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]()

day04-decorator的更多相关文章

  1. 设计模式(三):“花瓶+鲜花”中的装饰者模式(Decorator Pattern)

    在前两篇博客中详细的介绍了"策略模式"和“观察者模式”,今天我们就通过花瓶与鲜花的例子来类比一下“装饰模式”(Decorator Pattern).在“装饰模式”中很好的提现了开放 ...

  2. 设计模式(九)装饰者模式(Decorator Pattern)

    一.引言 在软件开发中,我们经常想要对一类对象添加不同的功能,例如要给手机添加贴膜,手机挂件,手机外壳等,如果此时利用继承来实现的话,就需要定义无数的类,如StickerPhone(贴膜是手机类).A ...

  3. Python之美--Decorator深入详解

    转自:http://www.cnblogs.com/SeasonLee/archive/2010/04/24/1719444.html 一些往事 在正式进入Decorator话题之前,请允许我讲一个小 ...

  4. C#设计模式系列:装饰模式(Decorator)

    1. 装饰模式简介 装饰模式动态地给一个对象添加额外的职责.例如一幅画有没有画框都可以挂在墙上,画就是被装饰者.但是通常都是有画框的.在挂在墙上之前,画可以被蒙上玻璃,装到框子里,所以在画上加一层画框 ...

  5. 装饰模式 - Decorator 和 外观模式 - Facade

    装饰模式 Decorator,不改变接口但动态给对象加入责任,所需功能按顺序串联起来控制,比生成子类灵活. 外观模式 Facade,让接口更简单.为子系统中的一组接口提供一个一致的界面. 参考:

  6. 设计模式学习之路——Decorator装饰模式(结构模式)

    子类复子类,子类何其多 假如我们需要为游戏中开发一种坦克,除了各种不同型号的坦克外,我们还希望在不同场合中为其增加以下一种或多种功能:比如红外线夜视功能,比如水陆两栖功能,比如卫星定位功能等等. 动机 ...

  7. angular中自定义依赖注入的方法和decorator修饰

    自定义依赖注入的方法 1.factory('name',function () { return function(){ } }); 2.provider('name',function(){ thi ...

  8. python嵌套函数、闭包与decorator

    1 一段代码的执行结果不光取决与代码中的符号,更多地是取决于代码中符号的意义,而运行时的意义是由名字空间决定的.名字空间是在运行时由python虚拟机动态维护的,但是有时候我们希望能将名字空间静态化. ...

  9. [工作中的设计模式]装饰模式decorator

    一.模式解析 装饰模式又名包装(Wrapper)模式.装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案. 装饰模式的要点主要是: 1.需要对已有对象扩展新的功能,又不希望改变原有对 ...

  10. python 中的decorator

    python 中decorator的作用就是一个包装的作用,所谓包装指在执行真正的函数之前或者之后,我们可以有一些额外的发挥余地. decorator形式如下 def dec(arg1): print ...

随机推荐

  1. 工作好搭档(一):松林 SL-B3 人体工学椅

    本人从事码农这行职业,已经整整十年零九天,十年一觉如旧梦,仿佛昨天还在SARS. 2008年,我累到腰痛,脖子痛,怎么休息也不见好,去中医院检查,医生诊断,坐的太久,坐姿不对,运动少,轻度颈椎,腰肌劳 ...

  2. Linux 系统查看tomcat控制台命令

    前提进入tomcat/logs文件夹下 查看全部命令是:tail -f catalina.out 如果想查看具体文件的日志进入该文件所在目录然后命令如下: tail -f filename

  3. 关于token,session,cookie的概念和区别

    记录几篇讲的比较好的文章 https://www.cnblogs.com/moyand/p/9047978.html https://blog.csdn.net/wabiaozia/article/d ...

  4. 【原创】多字节版本下MFC控件处理字符集的BUG

    工程项目属性: 字符集:多字节 stdafx.h文件中添加: #pragma comment(linker,"/manifestdependency:\"type='win32' ...

  5. cascade rcnn

    在region proposal阶段采用不同的iou. 第一幅图,不同颜色的线是用不同的region proposal的iou阈值,横坐标是region proposal生成的框与gt的原始iou,纵 ...

  6. Css3 实现关键帧动画

    <div class="person"> </div> <script> var str1 = "@keyframes move{&q ...

  7. Kernel Ridge Regression

    回顾一下岭回归,岭回归的目的是学习得到特征和因变量之间的映射关系,由于特征可能很高维,所以需要正则化 岭回归的目标函数是 $$ \sum_{i=1}^n \left\|y-X\beta\right\| ...

  8. UDP and TCP

    UDP unreliable, just add de-multiplexing and error checking on data than IP. Best effort datagram(数据 ...

  9. 阿贾克斯(AJAX)

    AJAX   :Asynchronous JavaScript and XML 异步的javascript 和xml 优点 : 在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分数据 不需要 ...

  10. 一点一点看JDK源码(五)java.util.ArrayList 后篇之SubList

    一点一点看JDK源码(五)java.util.ArrayList 后篇之SubList liuyuhang原创,未经允许禁止转载 本文举例使用的是JDK8的API 目录:一点一点看JDK源码(〇) S ...