一:编写函数,(函数执行的时间是随机的)
二:编写装饰器,为函数加上统计时间的功能
import time def timmer(func): def wrapper(*args,**kwargs): start = time.time() res = func(*args,**kwargs) stop = time.time() print('run time is %s' %(stop - start)) return res return wrapper @timmer def index(): print('welcome to index') time.sleep(3) return 123 @timmer def home(name): print('welcome %s to home page' %name) time.sleep(2) res = index() home('egon')
三:编写装饰器,为函数加上认证的功能
import time def auth(func): def wrapper(*args,**kwargs): tag = True while tag: name_inp = input('username>>: ').strip() pwd_inp = input('password>>: ') with open('db','rt',encoding='utf-8') as f: for line in f: line = line.strip(' ').split(':') if name_inp == line[0] and pwd_inp == line[1]: print('认证成功') tag = False break else: print('认证失败') res=func(*args,**kwargs) return res return wrapper @auth # index=auth(index) def index(): print('welcome to index') time.sleep(3) return 123 @auth # home=auth(home) def home(name): print('welcome %s to home page' %name) time.sleep(2) res=index() home('egon')
四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
db='db' login_status={'user':None,'status':False} def auth(auth_type='file'): def auth2(func): def wrapper(*args,**kwargs): if login_status['user'] and login_status['status']: return func(*args,**kwargs) if auth_type == 'file': with open(db,encoding='utf-8') as f: dic=eval(f.read()) name=input('username: ').strip() password=input('password: ').strip() if name in dic and password == dic[name]: login_status['user']=name login_status['status']=True res=func(*args,**kwargs) return res else: print('username or password error') elif auth_type == 'sql': pass else: pass return wrapper return auth2 @auth() def index(): print('index') @auth(auth_type='file') def home(name): print('welcome %s to home' %name) index() home('egon')
五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录
import time,random user={'user':None,'login_time':None,'timeout':0.000003,} def timmer(func): def wrapper(*args,**kwargs): s1=time.time() res=func(*args,**kwargs) s2=time.time() print('%s' %(s2-s1)) return res return wrapper def auth(func): def wrapper(*args,**kwargs): if user['user']: timeout=time.time()-user['login_time'] if timeout < user['timeout']: return func(*args,**kwargs) name=input('name>>: ').strip() password=input('password>>: ').strip() if name == 'egon' and password == '123': user['user']=name user['login_time']=time.time() res=func(*args,**kwargs) return res return wrapper @auth def index(): time.sleep(random.randrange(3)) print('welcome to index') @auth def home(name): time.sleep(random.randrange(3)) print('welcome %s to home ' %name) index() home('egon')