您可以使用格式为“owner_name/repo_name”的 get_repo() 将其从 3 个 API 调用减少到 2 个
from github import Github
gh = Github(access_token) # I supply an access token here.
repo = gh.get_repo(owner_name+'/'+repo_name) # This takes 1 API call
file = repo.get_file_contents(filename, ref=sha) # This takes 1 API call
只是在这里提到这一点以供将来参考。实际上,我最终使用了 requests 库并形成了自己的 api 调用。
像这样:
import requests
# Import python's base64 decoder
from base64 import b64decode as decode
def GET(owner_repo,filename,sha,access_token):
# Supply Headers
headers = {'content-type': 'application/json', 'Authorization':'token '+access_token}
# This function is stable so long as the github API structure does not change.
# Also I am using the previously mentioned combo of owner/repo.
url = 'https://api.github.com/repos/%s/contents/%s?ref=%s' % (owner_repo, filename, sha)
# Let's stay within the API rate limits
url_rate_limit = 'https://api.github.com/rate_limit'
r = requests.get(url_rate_limit, headers=headers)
rate_limit = int(r.json()['resources']['core']['remaining'])
if(rate_limit > 0):
# The actual request
r = requests.get(url, headers=headers)
# Note: you will need to handle the any error codes yourself.
# I am just safe checking for '200' OK
if(r.status_code == 200):
content = r.json()['content']
# Decode base64 content
decoded_content = decode(content)
return decoded_content
我在 MIT 许可下许可上述代码。