首页 > Web开发 > 详细

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

时间:2019-08-17 01:19:29      阅读:134      评论:0      收藏:0      [点我收藏+]
编写下载网页内容的函数,要求功能是:用户传入一个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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!