首页 > 解决方案 > 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运行,但对其他人运行正常呢?

标签: pythonpython-3.xapipostman

解决方案


推荐阅读