进阶作业(选做):
# 1.编写下载网页内容的函数,要求功能是:用户传入一个url,函数返回下载页面的结果
# 2.为题目1编写装饰器,实现缓存网页内容的功能:
# 具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先从文件中读取网页内容,否则,就去下载,然后存到文件
import os
from urllib.request import urlopen
dic = {}
i = 1
def cache(func):
def inner(*args, **kwargs):
global i
with open('%s.txt' % i, 'w') as f:
f.write('')
if args in dic.keys():
with open(str(dic[args])+'.txt', 'rb') as f:
return f.read()
if os.path.getsize('%s.txt' % i):
with open('%s.txt' % i, 'rb') as f:
return f.read()
ret = func(*args, **kwargs)
with open('%s.txt' % i, 'wb') as f:
f.write(b'**********' + ret)
dic.setdefault(args, i)
i += 1
print(dic)
return ret
return inner
@cache
def get_url(url):
code = urlopen(url).read()
return code
ret = get_url('http://www.baidu.com')
print(ret)
ret = get_url('http://www.baidu.com')
print(ret)
ret = get_url('http://www.cnblogs.com')
print(ret)