OpenWrt_Luci_Lua/1_7.http_proxy_server/python/testCode/cacheUtil.py

71 lines
2.1 KiB
Python
Raw Normal View History

2015-06-17 14:58:49 +00:00
#!/usr/bin/env python
# coding=utf-8
import urllib
import urllib2
2015-06-18 07:55:16 +00:00
import json
2015-06-17 14:58:49 +00:00
class CacheUtils:
2015-06-18 07:55:16 +00:00
@staticmethod
2015-06-17 14:58:49 +00:00
def cbk(a, b, c):
'''''回调函数
@a: 已经下载的数据块
@b: 数据块的大小
@c: 远程文件的大小
'''
per = 100.0 * a * b / c
if per > 100:
per = 100
print '%.2f%%' % per
def download(self, url, local):
2015-06-18 07:55:16 +00:00
urllib.urlretrieve(url, local, self.cbk)
2015-06-17 14:58:49 +00:00
2015-06-18 07:55:16 +00:00
def cache(self, url, range):
2015-06-17 14:58:49 +00:00
fileName = url.split('/')[-1]
req = urllib2.Request(url)
2015-06-18 07:55:16 +00:00
req.add_header('Range', 'bytes=' + range)
2015-06-17 14:58:49 +00:00
response = urllib2.urlopen(req)
buffer = response.read()
2015-06-18 07:55:16 +00:00
with open("./cache/" + fileName + range, "a+") as fp:
2015-06-17 14:58:49 +00:00
fp.write(buffer)
2015-06-19 11:54:34 +00:00
def saveReq(self, url, range):
2015-06-18 07:55:16 +00:00
# Reading data back
with open('data.json', 'r') as fp:
data = json.load(fp)
2015-06-19 11:54:34 +00:00
data[url] = range
2015-06-18 07:55:16 +00:00
# Writing JSON data
with open('data.json', 'w') as fp:
json.dump(data, fp)
2015-06-19 11:54:34 +00:00
def checkReq(self, url):
2015-06-18 07:55:16 +00:00
# Reading data back
with open('data.json', 'r') as fp:
data = json.load(fp)
2015-06-19 11:54:34 +00:00
if data.get(url):
fileName = url.split('/')[-1]
with open('GotIt.txt', 'a+') as fp:
if data[url] == "None":
fp.write("./download/" + fileName + "\n")
else:
fp.write("./cache/" + fileName + " " + data[url] + "\n")
return True
2015-06-18 07:55:16 +00:00
else:
2015-06-19 11:54:34 +00:00
return False
2015-06-18 07:55:16 +00:00
if __name__ == '__main__':
cacheUtils = CacheUtils()
#url = "http://www.sina.com.cn"
#fileName = url.split('/')[-1]
#cacheUtils.download(url, "./cache/" + fileName)
#cacheUtils.cache("http://www.baidu.com")
#cacheUtils.cache("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superplus/img/logo_white_ee663702.png", "0-7000")
#cacheUtils.cache("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superplus/img/logo_white_ee663702.png", "7001-14175")
2015-06-19 11:54:34 +00:00
#cacheUtils.saveReq("http://www.sina.com.cn")
2015-06-18 07:55:16 +00:00
#cacheUtils.loadReq()