如何使用github3.py查找复刻仓库的上游/父仓库?
如何用github3.py查找复刻仓库的父/上游仓库?
我懂你的困扰!用requests直接调用GitHub API拿父仓库信息确实简单,但github3.py好像把这个功能藏得有点隐蔽——其实它完全支持,只是你需要多一步操作来获取完整的仓库数据。
你之前发现repo.as_dict()里没有parent字段,是因为通过gh.repositories_by()获取的仓库列表是精简版数据,GitHub API默认返回的是简化后的仓库信息,并没有包含parent这类详细字段。这时候只需要调用仓库对象的refresh()方法,就能拉取完整的仓库详情,parent字段自然就有了!
给你写个完整的示例代码:
import github3 # 用GitHub令牌登录(推荐,比用户名密码更安全) gh = github3.login(token="你的GitHub访问令牌") target_username = "你要查询的用户名" for repo in gh.repositories_by(target_username): if repo.fork: # 刷新仓库,获取完整的API数据 repo.refresh() # 现在可以直接访问parent属性,它是一个Repository对象 parent_repo = repo.parent print(f"复刻仓库:{repo.full_name}") print(f"对应父仓库:{parent_repo.full_name}") print(f"父仓库网页地址:{parent_repo.html_url}") print("---")
这个方法比用requests更省心:github3.py已经帮你把JSON响应封装成了Repository对象,你不用自己解析字典,直接调用parent的属性(比如full_name、clone_url、description)就行,非常方便。
内容的提问来源于stack exchange,提问作者cclauss
相关产品推荐
相关产品推荐

