如何在Python中使用Github API?用法示例教程

2021年11月16日21:22:23 发表评论 2,127 次浏览

使用 Github API v3 在 Python 中使用请求和 PyGithub 库搜索存储库、用户、提交、删除文件等。

Github是一个Git存储库托管服务,其中添加了许多自己的功能,例如基于 Web 的图形界面来管理存储库、访问控制和其他一些功能,例如 wiki、组织、要点等。

Python如何使用Github API?你可能已经知道,有大量数据需要抓取。在本教程中,你将学习如何使用请求PyGithub库在 Python 中使用 Github API v3 。

首先,让我们安装依赖项:

pip3 install PyGithub requests

Python Github API用法示例:获取用户数据

由于使用Github API v3非常简单,你可以GET向特定 URL发出简单请求并检索结果:

import requests
from pprint import pprint

# github username
username = "x4nth055"
# url to request
url = f"https://api.github.com/users/{username}"
# make the request and return the json
user_data = requests.get(url).json()
# pretty print JSON data
pprint(user_data)

如何在Python中使用Github API?这里我使用了我的账户,这是返回的JSON的一部分(你也可以在浏览器中看到它):

{'avatar_url': 'https://avatars3.githubusercontent.com/u/37851086?v=4',
 'bio': None,
 'blog': 'https://www.thepythoncode.com',
 'company': None,
 'created_at': '2018-03-27T21:49:04Z',
 'email': None,
 'events_url': 'https://api.github.com/users/x4nth055/events{/privacy}',
 'followers': 93,
 'followers_url': 'https://api.github.com/users/x4nth055/followers',
 'following': 41,
 'following_url': 'https://api.github.com/users/x4nth055/following{/other_user}',
 'gists_url': 'https://api.github.com/users/x4nth055/gists{/gist_id}',
 'gravatar_id': '',
 'hireable': True,
 'html_url': 'https://github.com/x4nth055',
 'id': 37851086,
 'login': 'x4nth055',
 'name': 'Rockikz',
<..SNIPPED..>

大量数据,这就是为什么单独使用请求库手动提取大量数据并不方便的原因,因此,PyGithub出现了。

获取用户的公共存储库

Python如何使用Github API?让我们使用刚刚安装的 PyGithub 库获取该用户的所有公共存储库:

import base64
from github import Github
from pprint import pprint

# Github username
username = "x4nth055"
# pygithub object
g = Github()
# get that user by username
user = g.get_user(username)

for repo in user.get_repos():
    print(repo)

这是我的输出:

Repository(full_name="x4nth055/aind2-rnn")
Repository(full_name="x4nth055/awesome-algeria")
Repository(full_name="x4nth055/emotion-recognition-using-speech")
Repository(full_name="x4nth055/emotion-recognition-using-text")
Repository(full_name="x4nth055/food-reviews-sentiment-analysis")
Repository(full_name="x4nth055/hrk")
Repository(full_name="x4nth055/lp_simplex")
Repository(full_name="x4nth055/price-prediction")
Repository(full_name="x4nth055/product_recommendation")
Repository(full_name="x4nth055/pythoncode-tutorials")
Repository(full_name="x4nth055/sentiment_analysis_naive_bayes")

好的,所以我做了一个简单的函数来从这个Repository对象中提取一些有用的信息:

def print_repo(repo):
    # repository full name
    print("Full name:", repo.full_name)
    # repository description
    print("Description:", repo.description)
    # the date of when the repo was created
    print("Date created:", repo.created_at)
    # the date of the last git push
    print("Date of last push:", repo.pushed_at)
    # home website (if available)
    print("Home Page:", repo.homepage)
    # programming language
    print("Language:", repo.language)
    # number of forks
    print("Number of forks:", repo.forks)
    # number of stars
    print("Number of stars:", repo.stargazers_count)
    print("-"*50)
    # repository content (files & directories)
    print("Contents:")
    for content in repo.get_contents(""):
        print(content)
    try:
        # repo license
        print("License:", base64.b64decode(repo.get_license().content.encode()).decode())
    except:
        pass

如何在Python中使用Github API?Repository 对象还有很多其他的字段,建议你使用dir(repo)获取你想要打印的字段。让我们再次遍历存储库并使用我们刚刚编写的函数:

# iterate over all public repositories
for repo in user.get_repos():
    print_repo(repo)
    print("="*100)

这将打印有关此用户的每个公共存储库的一些信息:

====================================================================================================
Full name: x4nth055/pythoncode-tutorials
Description: The Python Code Tutorials
Date created: 2019-07-29 12:35:40
Date of last push: 2020-04-02 15:12:38
Home Page: https://www.thepythoncode.com
Language: Python
Number of forks: 154
Number of stars: 150
--------------------------------------------------
Contents:
ContentFile(path="LICENSE")
ContentFile(path="README.md")
ContentFile(path="ethical-hacking")
ContentFile(path="general")
ContentFile(path="images")
ContentFile(path="machine-learning")
ContentFile(path="python-standard-library")
ContentFile(path="scapy")
ContentFile(path="web-scraping")
License: MIT License
<..SNIPPED..>

我截断了整个输出,因为它将返回所有存储库及其信息,你可以看到我们使用repo.get_contents("")方法来检索该存储库的所有文件和文件夹,PyGithub将其解析为ContentFile对象,用于dir(content)查看其他有用的字段。

此外,如果你有私有存储库,你可以通过使用PyGithub验证你的帐户(使用正确的凭据)来访问它们,如下所示:

username = "username"
password = "password"

# authenticate to github
g = Github(username, password)
# get the authenticated user
user = g.get_user()
for repo in user.get_repos():
    print_repo(repo)

Github 还建议使用经过身份验证的请求,因为如果你使用公共 请求(未经身份验证)并且超过少量请求,它将引发RateLimitExceededException。

Python如何使用Github API?搜索存储库

Github API 非常丰富,你可以像在网站中一样通过特定查询来搜索存储库:

# search repositories by name
for repo in g.search_repositories("pythoncode tutorials"):
    # print repository details
    print_repo(repo)

这将返回9 个存储库及其信息。

你还可以按编程语言或主题进行搜索:

# search by programming language
for i, repo in enumerate(g.search_repositories("language:python")):
    print_repo(repo)
    print("="*100)
    if i == 9:
        break

要搜索特定主题,你只需"topic:machine-learning"search_repositories()method 中放入类似内容即可。

操作存储库中的文件

Python Github API用法示例:如果你使用的是经过身份验证的版本,你还可以使用 API 非常轻松地创建、更新和删除文件:

# searching for my repository
repo = g.search_repositories("pythoncode tutorials")[0]

# create a file and commit n push
repo.create_file("test.txt", "commit message", "content of the file")

# delete that created file
contents = repo.get_contents("test.txt")
repo.delete_file(contents.path, "remove test.txt", contents.sha)

如何在Python中使用Github API?上面的代码是一个简单的用例,我搜索了一个特定的存储库,我添加了一个新文件并调用了它test.txt,我将一些内容放入其中并进行了提交。之后,我抓取了那个新文件的内容并删除了它(它也算作一次 git 提交)。

果然,在执行上述代码行之后,提交被创建和推送:

如何在Python中使用Github API?用法示例教程
结论

Python如何使用Github API?我们刚刚在 Github API 中触及了皮毛,你可以使用许多其他功能和方法,显然,我们无法涵盖所有​​这些功能和方法,以下是一些有用的功能和方法,你可以自己测试它们:

  • g.get_organization(login):返回代表 Github 组织的Organization对象
  • g.get_gist(id) : 返回一个Gist对象,它代表 Github 中的一个要点
  • g.search_code(query):返回ContentFile对象的分页列表,其中表示多个存储库中的匹配文件
  • g.search_topics(query):返回一个Topic对象的分页列表,其中它代表一个 Github 主题
  • g.search_commits(query):返回Commit对象的分页列表,其中它代表 Github 中的提交

还有很多,请使用dir(g)获取其他方法,查看PyGithub 文档,或Github API以获取详细信息。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: