python - 使用 with open 缓存来自 Web API 的结果
问题描述
我正在使用从 WEB-api 返回的大量数据。下面的函数调用 API 22 次,将 json 解码并加载为 python 格式。然后我将结果存储在一个 22 页的大列表中,每 100 个艺术品作为数据。
fourteen_list = return_14th_century_works_list()
为了限制必要的 API 调用,我想构建一个函数,将这个列表存储为一个文件(如果它不存在),当它存在时我想从我的计算机加载文件。我想出了以下内容:
with open('fourteenth_century_list.txt', 'w') as fourteenth_century_file:
print(fourteen_list, file=fourteenth_century_file)
try:
with open('fourteenth_century_list.txt', 'r') as fourteenth_century_file:
fourteenth_list_cache = fourteenth_century_file.read()
count_objects(fourteenth_list_cache)
except FileNotFoundError:
fourteenth_list = return_14th_century_works_list() Calls API again
count_objects(fourteen_list)
我使用 count_objects 函数检查一切是否仍然有效,但在 try 块中打开的文件似乎与我保存它的方式不同;当我运行这段代码时,try-block 中的函数调用返回一个类型错误。对我来说,这表明从磁盘打开的文件的格式与我直接从 API 加载时的格式有所不同。
当我使用列表的非缓存版本调用函数 count_objects() 时,在这种情况下,fourteen_list 可以正常工作。
with_open(filename, 'w') 然后 with_open(filename, 'r') 是否会改变您的数据,如果不是,我在这里做错了什么?
解决方案
这里的问题是,当您print
将字典列表添加到文件时,您会创建列表的字符串表示形式。然后,您读回该字符串并将其传递给count_objects()
,但这会失败,因为它需要一个字典列表,而不是一个大字符串。
而不是打印,更好的方法是将列表序列化以支持 JSON - 这将保留其结构。从 API 检索数据后,您还希望将列表写入except
块中的缓存。
import json
try:
with open('fourteenth_century_list.json', 'r') as fourteenth_century_file:
fourteenth_list_cache = json.load(fourteenth_century_file)
count_objects(fourteenth_list_cache)
except FileNotFoundError:
# Calls API again
fourteenth_list = return_14th_century_works_list()
count_objects(fourteen_list)
# Cache the API data
with open('fourteenth_century_list.json', 'w') as fourteenth_century_file:
json.dump(fourteen_list, fourteenth_century_file)
推荐阅读
- java - 将字符串解析为 Integer/Long/Float/Double
- debugging - WebFOCUS 的调试策略和工具
- docker - 如何在docker overlay2中使本机覆盖差异为假?
- jquery - NodeJS async/await 不等待先前的请求响应
- android - 我想在我的选项卡上制作导航视图,您可以单击 3 栏来导航视图。我怎么做?
- excel - Excel 宏 - 无法运行 .exe 文件
- python - Tensorflow Keras - AttributeError:图层特征没有入站节点
- excel - 仅在某些列中查找值
- c# - C# - 将反射与 JsonSchema4.FromTypeAsync 结合使用
- snakemake - snakemake --list-code-changes 不会传播到子工作流中