【发布时间】:2016-03-28 01:18:49
【问题描述】:
我有一个脚本,它对从 API 返回到平面文件的数据作为 JSON 对象进行一些可怜的缓存。每行一个结果/JSON 对象。
缓存工作流程如下:
读取整个缓存文件 -> 逐行检查每一行是否太旧 -> 将不太旧的保存到新列表 -> 打印新的新缓存列表到文件中,并且还使用新列表作为过滤器,以不处理 API 调用的传入数据。
到目前为止,这个过程中最长的部分在上面用粗体表示。代码如下:
print "Reading cache file into memory ---"
with open('cache', 'r') as f:
cache_lines = f.readlines()
print "Turning cache lines into json and checking if they are stale or not ---"
for line in cache_lines
# Load the line back up as a json object
try:
json_line = json.loads(line)
except Exception as e:
print e
# Get the delta to determine if data is stale.
delta = meta_dict["timestamp_start"] - parser.parse(json_line['timestamp_start'])
# If the data is still fresh then hold onto it
if cache_timeout >= delta:
fresh_cache.append(json_line)
这可能需要几分钟,具体取决于哈希文件的大小。有没有更快的方法来做到这一点?我知道读取整个文件一开始并不理想,但它最容易实现。
【问题讨论】:
标签: python performance file caching