python是谁在维护更新_在Python中维护网页的更新文件缓存?

我不认为有一个库可以做到这一点,但它并不难实现。以下是我在请求中使用的一些函数,可能会对您有所帮助:import os

import os.path as op

import requests

import urlparse

CACHE = 'path/to/cache'

def _file_from_url(url):

return op.basename(urlparse.urlsplit(url).path)

def is_cached(*args, **kwargs):

url = kwargs.get('url', args[0] if args else None)

path = op.join(CACHE, _file_from_url(url))

if not op.isfile(path):

return False

res = requests.head(*args, **kwargs)

if not res.ok:

return False

# Check if cache is stale. For me, checking content-length fitted my use case.

# You can use modification date or etag here:

if not 'content-length' in res.headers:

return False

return op.getsize(path) == int(res.headers['content-length'])

def update_cache(*args, **kwargs):

url = kwargs.get('url', args[0] if args else None)

path = op.join(CACHE, _file_from_url(url))

res = requests.get(*args, **kwargs)

if res.ok:

with open(path, 'wb') as handle:

for block in res.iter_content(1024):

if block:

handle.write(block)

handle.flush()

用法:

^{pr2}$

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值