装饰器 练习二

 

from urllib.request import urlopen
import os.path


def cache(func):
    def inner(*args, **kwargs):

        if os.path.getsize("web_cache"):
            with open("web_cache", 'rb') as f:  # 一定要注意 对网络内容 都是以字节进行读写 rb wb
                return f.read()

        ret = func(*args, **kwargs)

        # 将网页内容缓存下来,写入文件
        with open("web_cache", 'wb') as f:   # 一定要注意 对网络内容 都是以字节进行读写 rb wb
            f.write(b'**cache**'+ret)  # 为标识区分 缓存文件中内容与网络内容的不同 人为添加字节字符串 b'**cache**'

        return ret
    return inner

@cache
def getWebPage(url):
    content = urlopen(url).read()  # 打开网址 读取网页内容
    return content  # 网页内容

# 第一次执行 获取网页内容做为返回值 并写入文件做为本地缓存
ret = getWebPage("http://www.baidu.com")
print(ret)
# 第二次执行 优先判定本地文件有内容 则读文件内容做为 返回值
ret = getWebPage("http://www.baidu.com")
print(ret)

 

posted @ 2020-05-05 16:04  CherryYang  阅读(72)  评论(0)    收藏  举报