编写装饰器,实现缓存网页内容的功能

编写下载网页内容的函数,要求功能是:用户传入一个url,函数返回下载页面的结果并编写装饰器,实现缓存网页内容的功能:
具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先从文件中读取网页内容,否则,就去下载,然后存到文件中
import os
from urllib.request import urlopen
def cache(func):
    def inner(*args,**kwargs):
        if os.path.getsize('网页缓存'):
            with open('网页缓存','rb') as f:
                return f.read()
        ret = func(*args,**kwargs)
        with open('网页缓存','wb') as f:
            f.write(ret)
        return ret
    return inner

@cache
def new_cache(url):
    code = urlopen(url).read()
    return code
ret = new_cache('http://www.baidu.com')
print(ret)

 网页有缓存时:

 网页无缓存时:

 知识点:

文件操作

os模块与url模块的使用:

  os.path.getsize(),判断文件是否为空

  urlopen(网址).read(),读取网页的源码,即缓存

原文地址:https://www.cnblogs.com/aizhinong/p/11366336.html