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

标签 python python-2.7 python-requests github-api

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

但是,当我第一次请求特定网址时,我得到了一个空字典响应。第二次请求相同的 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 工作正常,请解释为什么它会发生在“贡献者”身上。

First time result

Second time result

最佳答案

我相信这是由于生成统计数据需要进行计算造成的。 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' 请求 = requests.get(contributors_url) 打印请求.status_code

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

关于Python 需要请求 GitHub/API/repo/statistics/contributors url 两次才能获取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31442518/

相关文章:

python - 运行 fastStructure 时出错 : ImportError: No module named allelefreq

python - Caffe 编译时没有看到 hdf5.h

python - 如何使用 python 2.7 关闭 cmd 窗口

python - POST 请求后获取响应/返回值(python 请求)

python - 访问被拒绝的 Python 脚本 Pstuil

python - 为什么 Python 的原始字符串文字不能以单个反斜杠结尾?

Python 2 多处理映射,无需耗尽生成器

python - 使用 BeautifulSoup 无法按预期解析 XML

python-3.x - Cloud Natural Language API 返回 socket.gaierror : nodename nor servname provided after performing Sentiment Analysis every now and then

Python requests_ntlm导入错误