Python需要请求GitHub/API/repo/statistics/contributorsurl两次才能获取内容

Python need to request GitHub/API/repo/statistics/contributors url twice to get content

我想获取特定存储库的贡献者及其提交总数。我正在使用 Python 2.7 和 Requests 2.7.0 库来请求 GitHub API url 就像:'https://api.github.com/repos/marcboeker/mongodb-utils/stats/contributors'(这是一个随机的 link, 对不起 marcboeker ^_^).

但是,我第一次请求特定 url 时,得到的是空字典响应。我第二次请求相同的 url,我可以获得包含我需要的信息的列表。这是我的代码:

import requests

contributors_url = 'https://api.github.com/repos/marcboeker/mongodb-utils/stats/contributors'
contributors = requests.get(contributors_url).json()
print contributors

我也试过用GitHub认证,试过用urllib2库。我也在 Python 3.4 中尝试过。但我得到了相同的结果。 我需要在第一次请求 url 时获得正确的结果,而不是第二次或第三次。由于其他 GitHub API url 工作正常,请解释为什么它发生在 'contributors'.

我认为这是因为生成统计信息需要进行计算。 API documentation 概述了这一点:

If the data hasn’t been cached when you query a repository’s statistics, you’ll receive a 202 response; a background job is also fired to start compiling these statistics. Give the job a few moments to complete, and then submit the request again. If the job has completed, that request will receive a 200 response with the statistics in the response body.

您能否检查请求中的状态代码以验证它是否为空响应:

contributors_url = 'https://api.github.com/repos/marcboeker/mongodb-utils/stats/contributors' request = requests.get(contributors_url) print request.status_code

我在一个新的存储库上使用 Fiddler 对此进行了测试,并收到了 202 状态代码和一个空的 JSON 数组作为响应。所以我认为您需要检查该状态代码,然后在延迟后重试调用...