day04-decorator
# 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的更多相关文章
- 设计模式(三):“花瓶+鲜花”中的装饰者模式(Decorator Pattern)
在前两篇博客中详细的介绍了"策略模式"和“观察者模式”,今天我们就通过花瓶与鲜花的例子来类比一下“装饰模式”(Decorator Pattern).在“装饰模式”中很好的提现了开放 ...
- 设计模式(九)装饰者模式(Decorator Pattern)
一.引言 在软件开发中,我们经常想要对一类对象添加不同的功能,例如要给手机添加贴膜,手机挂件,手机外壳等,如果此时利用继承来实现的话,就需要定义无数的类,如StickerPhone(贴膜是手机类).A ...
- Python之美--Decorator深入详解
转自:http://www.cnblogs.com/SeasonLee/archive/2010/04/24/1719444.html 一些往事 在正式进入Decorator话题之前,请允许我讲一个小 ...
- C#设计模式系列:装饰模式(Decorator)
1. 装饰模式简介 装饰模式动态地给一个对象添加额外的职责.例如一幅画有没有画框都可以挂在墙上,画就是被装饰者.但是通常都是有画框的.在挂在墙上之前,画可以被蒙上玻璃,装到框子里,所以在画上加一层画框 ...
- 装饰模式 - Decorator 和 外观模式 - Facade
装饰模式 Decorator,不改变接口但动态给对象加入责任,所需功能按顺序串联起来控制,比生成子类灵活. 外观模式 Facade,让接口更简单.为子系统中的一组接口提供一个一致的界面. 参考:
- 设计模式学习之路——Decorator装饰模式(结构模式)
子类复子类,子类何其多 假如我们需要为游戏中开发一种坦克,除了各种不同型号的坦克外,我们还希望在不同场合中为其增加以下一种或多种功能:比如红外线夜视功能,比如水陆两栖功能,比如卫星定位功能等等. 动机 ...
- angular中自定义依赖注入的方法和decorator修饰
自定义依赖注入的方法 1.factory('name',function () { return function(){ } }); 2.provider('name',function(){ thi ...
- python嵌套函数、闭包与decorator
1 一段代码的执行结果不光取决与代码中的符号,更多地是取决于代码中符号的意义,而运行时的意义是由名字空间决定的.名字空间是在运行时由python虚拟机动态维护的,但是有时候我们希望能将名字空间静态化. ...
- [工作中的设计模式]装饰模式decorator
一.模式解析 装饰模式又名包装(Wrapper)模式.装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案. 装饰模式的要点主要是: 1.需要对已有对象扩展新的功能,又不希望改变原有对 ...
- python 中的decorator
python 中decorator的作用就是一个包装的作用,所谓包装指在执行真正的函数之前或者之后,我们可以有一些额外的发挥余地. decorator形式如下 def dec(arg1): print ...
随机推荐
- C++ 构造转换函数和强制转换函数
http://blog.csdn.net/chenyiming_1990/article/details/8862497 1.对于系统的预定义基本类型数据,C++提供了两种类型转换方式:隐式类型转换和 ...
- pt-index-usage
pt-index-usage能够从日志当中分析索引的使用情况,并且生成一个报表.下面看一下基本的语法: pt-index-usage [OPTIONS] [FIILE] 打印报告: pt-index- ...
- DataS-2
2.4 证明对任意常数k,(称此式为公式A) 证明: ①当k1<k2时,,因此只需证明正数对公式A成立: ②当k=0或1时,显然有和满足公式A: ③假设k<i (i>1)时,都满足公 ...
- 【Leetcode】【Medium】Sum Root to Leaf Numbers (未完成)
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number ...
- 装有多个版本 office,选择默认的版本 打开文件
以下以office 2013 64位为例: 一.先打开运行窗口,Win + R 键: 二. 把office安装路径:"C:\Program Files\Microsoft Office\Of ...
- TIAGO机器人传感器参数简介 手册翻译
本来认为这篇文章是最没人气的,竟然收到了回复,看来要继续更新本文了.留下笔者联系方式,邮箱leop22@163.com,欢迎邮件交流. 防止不良爬虫,原文链接:http://www.cnblogs.c ...
- 微软在线 VSTS/TFS 使用简介,如何删除项目,帐号,获取git地址等
名称:微软 VSTS 全称: Visual Studio Team Services 地址:https://www.visualstudio.com/zh-hans/ 说明:注册就可以了使用了(如何使 ...
- February 15 2017 Week 7 Wednesday
Youth is not a time of life, it is a state of mind. 青春不是一段年华,而是一种心境. Likewise, maturity is not a tim ...
- SAP HANA Delivery Unit概念简述
介绍 在SAP HANA应用开发领域里,我们通常用package来存储modeler views和XS工程等模型.这些包应该被部署到最终的生产服务器上. Delivery Unit是SAP HANA原 ...
- mybatis实现最简单的增删改查
1.数据库设计 2.项目结构(针对User不用管Blogger) User.java package com.yunqing.mybatis.bean; public class User { pri ...