python - Python & API:为什么我在 python 运行时得到 KeyErrors 但邮递员中有值?
问题描述
我正在使用下面的代码从 Harvest 返回原始 json 数据,通过更改名为我已成功创建 6 个文件的运行脚本的 URL,但是我遇到了一个问题,我无法弄清楚为什么......
import requests, json
AUTH = "Bearer REDACTED"
ACCOUNT = "REDACTED"
URL = "https://api.harvestapp.com/v2/clients/?"
HEADERS = { "Authorization": AUTH,
"Harvest-Account-ID": ACCOUNT,
"Accept":"application/json"}
r = requests.get(url=URL, headers=HEADERS).json()
total_pages = int(r['total_pages'])
total_entries = int(r['total_entries'])
results = []
for x in range(1, total_pages):
response = requests.get(URL+"page="+str(x), headers=HEADERS)
data = response.json()
next_page = data["next_page"]
results.extend(data["time_entries"])
filepath = "Z:/System Administrator/System Backups/08. Harvest/HARVEST_Clients.json"
with open(filepath, 'w') as outfile:
json.dump(results, outfile)
print('Done!')
print('Total Pages : '+str(total_pages))
print('Total Entries : '+str(total_entries))
当我运行上述内容时,它给了我
完成的预期结果!
总页数:3
总条目:237
但是,如果我尝试使用带有日期变量的 URL,我会得到 KeyErrors。我所做的就是将代码更改为:
URL = "https://api.harvestapp.com/v2/clients/?"
至
URL = "https://api.harvestapp.com/v2/time_entries?from=2017-04-01&to=2018-03-31/?"
和 results.extend 变量来自
results.extend(data["clients"])
至
results.extend(data["time_entries"])
我得到错误
回溯(最后一次调用):文件“Z:\System Administrator\System Backups\08.Harvest\Scripts\API_Harvest_Timesheets 2017-18.py”,第 19 行,在 total_pages = int(r['total_pages']) KeyError: “总页数”
当我通过邮递员运行 URL 和授权时,我得到以下结果
{
"time_entries": [FULL DATA RESULT HERE]
"per_page": 100,
"total_pages": 138,
"total_entries": 13711,
"next_page": 2,
"previous_page": null,
"page": 1,
"links": {
"first": "https://api.harvestapp.com/v2/time_entries?from=2017-04-01&page=1&per_page=100&to=2018-03-31",
"next": "https://api.harvestapp.com/v2/time_entries?from=2017-04-01&page=2&per_page=100&to=2018-03-31",
"previous": null,
"last": "https://api.harvestapp.com/v2/time_entries?from=2017-04-01&page=138&per_page=100&to=2018-03-31"
}
}
所以我可以看到'total_pages'值是从那个url返回的,值为138 - 那么为什么这段代码不能为这个特定的URL运行,但对其他人运行正常呢?
解决方案
推荐阅读
- arrays - 如何使用冒号运算符将半整数序列压缩为字符串表达式?(如何将列表转换为字符串)
- r - 在经度和纬度上填充渐变
- arrays - 用户定义函数,用于在一个参数中输入多个单元格时返回结果
- xml - XSL - 如何在另一个循环中为每个循环下一个链接来自不同 xml 节点的相同值
- node.js - 在我的 NodeJS 程序中,为什么我的数组没有定义
- c++ - 有条件地包含 C++ 标准库
- docker - 如何使用 Github Actions 登录 Docker 注册表
- ruby-on-rails - 如何在 rails 关联中包含连接表中的列?
- php - 无法打开流:/home/maxim/Documents/Programming/PHP/autoload.php 中没有这样的文件或目录
- c# - 使用 JSON.NET 进行递归 JSON 解析