# 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. MySQL数据操作(借鉴)

    /* 启动MySQL */net start mysql /* 连接与断开服务器 */mysql -h 地址 -P 端口 -u 用户名 -p 密码 /* 跳过权限验证登录MySQL */mysqld ...

  2. eclipse tomcat jdk 版本引用

    今日遇到一个问题,因为比较难找,所以记录下来,方便日后查阅,也许也可以帮助同行. 一个Java project工程,使用了solr6.2,所以需要引用jdk8才可以正常使用. 代码编写好了,已经提交s ...

  3. 【转】Java中的String,StringBuilder,StringBuffer三者的区别

    https://www.cnblogs.com/su-feng/p/6659064.html 最近在学习Java的时候,遇到了这样一个问题,就是String,StringBuilder以及String ...

  4. Oracle 12C pluggable database自启动

    实验环境创建了两个PDB,本实验实现在开启数据库时,实现pluggable database PDB2自启动: 原始环境: SQL> shu immediateDatabase closed.D ...

  5. Hibernate缓存策略

    Hibernate的一级缓存又称为Session缓存,其适用范围是在当前的会话之中,其生命周期和Session相同,随着Session的销毁,一级缓存也会随之销毁.一级缓存是不能取消的,Hiberna ...

  6. 前端面试题总结(一)HTML篇

    前端面试题总结(一)HTML篇 一.iframe的优缺点? 缺点: 1.会阻塞主页面的onload事件(iframe和主页面共享链接池,而浏览器对相同域的链接有限制,所以会影响页面的并行加载). 解决 ...

  7. python 获取某个月的全部日期

    import calendar print range(calendar.monthrange(year, month)[1]+1)[1:]

  8. Jmeter-常用函数之__CSVRead使用

    可参照:http://www.cnblogs.com/liu-ke/p/4324157.html 压测中有些参数是固定范围内的取值,或者成对出现(如登录帐号和密码),以大量用户同时登录网站为例: 1. ...

  9. webAPI请求消息过滤器

    每当制作一个WebAPI,就必然会收到外部很多调用这个API的请求,有时候,我们希望,能从这些外部来的请求中,按照一定条件筛选过滤一下,只将那些我们觉得合法的,有必要回应的请求放进来,一方面挡住那些非 ...

  10. Kindeditor图片上传Controller

    asp.net MVC Kindeditor 图片.文件上传所用的Controller [HttpPost, AllowAnonymous] public ActionResult UploadIma ...