Python&API:为什么用Python运行时会出现KeyErrors,而postman中却有这个值?

2024-05-13 14:30:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用下面的代码返回来自Harvest的原始json数据,通过更改名为的URL,我已经成功地为6个文件创建了运行脚本,但是我遇到了一个问题,我不知道为什么

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"])

我得到了错误

Traceback (most recent call last): File "Z:\System Administrator\System Backups\08. Harvest\Scripts\API_Harvest_Timesheets 2017-18.py", line 19, in total_pages = int(r['total_pages']) KeyError: 'total_pages'

当我通过postman运行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运行,而针对其他url运行良好呢


Tags: httpscomapijsonurldatatimepage