day 11 - 2 装饰器练习
1、编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件)要求登录成功一次,后续的函数都无需再输入用户名和密码
FLAG = False def login(func): def inner(*args,**kwargs): global FLAG if FLAG: ret = func(*args,**kwargs) return ret else: #登录程序 username = input('请输入用户名:') password = input('请输入密码:') if username == 'ysg' and password == "275": FLAG = True ret = func(*args,**kwargs) return ret else: print("登录失败") return inner @login def shoplist_add(): print("向购物车中添加物品") @login def shoplist_del(): print("向购物车中添加物品") shoplist_add() shoplist_del()
FLAG = False def login(f): def inner(*args,**kwargs): #判断是否以成功登录 global FLAG if FLAG: ret = f(*args,**kwargs) return else: #登录验证 use = input('>>>') pwd = input('>>>') lis=[] with open('E:/py/info.txt','r',encoding='utf-8')as info: for i in info: lis.append(i) if use == lis[0].strip() and pwd == lis[1].strip(): print('登陆成功') FLAG = True ret = f(*args,**kwargs) return ret else: print('登录失败') return inner @login def shoping(): print('在购物') @login def money(): print('在支付') shoping() money()
2、编写装饰器,为多个函数加上记录调用功能,要求每次调用函数都将被调用的函数名称写入文件
def log(func): def inner(*arge,**kwargs): with open('E:/py/log/log.txt','a',encoding='utf-8') as f: f.write(func.__name__ + '\n') ret = func(*arge,**kwargs) print("") return ret return inner @log def shoplist_add(): print("购买了一件商品") @log def shoplist_del(): print("删除了一件商品") shoplist_add() shoplist_del() shoplist_add() shoplist_del() shoplist_add() shoplist_del()
进阶练习:
1.编写下载网页内容的函数,要求功能是:用户传入一个url,函数返回下载页面的结果
2.为题目1编写装饰器,实现缓存网页内容的功能:
具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先文件中读取网页内容,否则,就去下载,然后存到文件中
import os from urllib.request import urlopen def cache(func): def inner(*arge,**kwargs): if os.path.getsize('E:/py/log/url.txt'): with open ("E:/py/log/url.txt","rb") as f: return f.read() ret = func(*arge,**kwargs) with open('E:/py/log/url.txt','wb') as f: f.write(ret+b"*****") return ret return inner @cache def get(url): code = urlopen(url).read() return code ret = get('http://www.baidu.com') print(ret) ret = get('http://www.baidu.com') print(ret)