【问题标题】:Github API: how to check if repository is empty?Github API:如何检查存储库是否为空?
【发布时间】:2015-10-28 18:03:09
【问题描述】:

我正在使用 pygithub3 库来解析用户存储库,但有时它会在请求失败后在断言上崩溃。起初我怀疑我已经达到了速率限制,但很快我意识到我可以 100% 在“空”存储库上重现断言(参见示例)。

https://github.com/poelzi/vaultfs

我将如何检查存储库是否可用? 简化代码sn-p:

for repo in gh.repos.list(user=author).all():
   ...
   contributors = repo.list_contributors(user=repo.owner.login, repo=repo.name).all()

它适用于 99% 的情况,但是当我遇到空存储库时,它会崩溃,我找不到任何“检测”它的方法。

【问题讨论】:

  • 您可以访问响应状态码吗?如果是这样,您应该检查响应代码是否为204。如果是这样,那么存储库是空的。 Here 是一篇关于此的博文。
  • 这很有帮助,会研究一下
  • 发布了答案。希望它有所帮助:)

标签: github-api pygithub


【解决方案1】:

您在 PyGithub 标签下的问题,下面是在该库中执行此操作的一种可能方法。

import github
from github import GithubException

g = github.Github(token)

# or if you are using login and password g = github.Github(login, password)
repo = g.get_repo("poelzi/vaultfs")

try:
    # get repo content from root directory
    repo.get_contents("/")
except GithubException as e:
    print(e.args[1]['message']) # output: This repository is empty.

【讨论】:

    【解决方案2】:

    根据this blog post,空存储库的贡献者端点响应代码是204 No Content

    这是一些相关的curl 输出:

    curl -v https://api.github.com/repos/poelzi/vaultfs/stats/contributors 
    *   Trying 192.30.252.127...
    * Connected to api.github.com (192.30.252.127) port 443 (#0)
    * found 187 certificates in /etc/ssl/certs/ca-certificates.crt
    * found 758 certificates in /etc/ssl/certs
    * ALPN, offering http/1.1
    ...
    < HTTP/1.1 204 No Content
    < Server: GitHub.com
    < Date: Wed, 28 Oct 2015 20:10:10 GMT
    < Status: 204 No Content
    ...
    

    查看pygithub 文档,我发现这已经是内置的:

    Repository.get_stats_contributors()

    调用GET /repos/:owner/:repo/stats/contributors 端点。

    这是调用此端点的唯一方法。

    此方法在空存储库上返回 None,在尚未计算统计信息时返回空列表。

    返回类型:无或Repository.StatsContributor列表

    也就是说,您必须检查返回值。如果没有,则存储库为空。

    【讨论】:

    • 支持努力,即使 v2 和 v3 库并不完全相同(或根本不一样)。
    • @AoeAoe 在我看来,没有v3 版本的库。当然,GitHub API 版本是v3,但PyGithub 版本是v2
    猜你喜欢
    • 2011-09-08
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 2015-11-05
    • 2022-11-20
    • 1970-01-01
    相关资源
    最近更新 更多