|
1、编写装饰器,为多个函数加上认证的功能(用户的账号和密码来源于文件),要求登录成功一次,后续的函数都无序输入用户名和密码。
FLAGE = False def login(func): def inner(*args,**kwargs): global FLAGE '''登录程序''' if FLAGE: ret = func(*args, **kwargs) return ret else: username = input('username:') password = input('password:') if username == 'boss_gold' and password == '2222': FLAGE = True else: print('登录失败') return inner @login def shoplist_add(): print('增加一件物品') @login def shoplist_del(): print('删除一件物品') shoplist_add() shoplist_del()
2、编写装饰器,为多个函数加上记录调用功能,要求每次调用函数都将被调用函数名称写入文件
def log(func): def inner(*args,**kwargs): with open('d:\\huangshurui.txt','a',encoding='utf-8') as f: f.write(func.__name__+'\n') ret = func(*args,**kwargs) # f.write(ret) return ret return inner @log def transfer(): print('增加一件物品') @log def transfer1(): print('删除一件物品') transfer() transfer1()
3、
(1)编写下载网页内容的函数,要求功能:用户传入一个url,函数返回下载页面的结果。
from urllib.request import urlopen def get(url): code = urlopen(url).read() print(code) return code ret=get('http://blog.sciencenet.cn/home.php?mod=space&uid=3405644&view=yiruia') print(ret)
(2)为题目1编写装饰器,实现缓存网页内容的功能。具体实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就先从文件中读取,否则去下载。
import os from urllib.request import urlopen def cache(func): def inner(*args,**kwargs): if os.path.getsize('web_cache'): # 判断文件大小,看文件中是否有内容 with open('web_cache','rb') as f: return f.read() ret = func(*args,**kwargs) # 请求网页的函数 with open('web_cache','wb') as f: #wb模式不用编码,0,1形式,将请求的结果写在文件中 f.write(b'****'+ret) return ret return inner @cache #get = cache(get) def get(url): code = urlopen(url).read() return code #{'网址':'文件名'} ret=get('http://blog.sciencenet.cn/home.php?mod=space&uid=3405644&view=yiruia') print(ret) ret=get('http://blog.sciencenet.cn/home.php?mod=space&uid=3405644&view=yiruia') print(ret) ret=get('http://blog.sciencenet.cn/home.php?mod=space&uid=3405644&view=yiruia') print(ret)
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-5-20 02:14
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社