从PyGithub高效获取最新提交URL

时间:2015-04-20 22:45:06

标签: python git github pygithub

我正在使用此功能使用PyGithub获取最新的提交网址:

from github import Github

def getLastCommitURL():
    encrypted = 'mypassword'
    # naiveDecrypt defined elsewhere
    g = Github('myusername', naiveDecrypt(encrypted))
    org = g.get_organization('mycompany')
    code = org.get_repo('therepo')
    commits = code.get_commits()
    last = commits[0]
    return last.html_url

它可以工作,但似乎让Github对我的IP地址不满意,并且对我产生的网址反应迟钝。我有更有效的方法吗?

2 个答案:

答案 0 :(得分:3)

如果您在过去24小时内没有提交,则无效。但是如果你这样做,它似乎返回得更快,并且会根据Github API documentation请求更少的提交:

from datetime import datetime, timedelta

def getLastCommitURL():
    encrypted = 'mypassword'
    g = Github('myusername', naiveDecrypt(encrypted))
    org = g.get_organization('mycompany')
    code = org.get_repo('therepo')
    # limit to commits in past 24 hours
    since = datetime.now() - timedelta(days=1)
    commits = code.get_commits(since=since)
    last = commits[0]
    return last.html_url

答案 1 :(得分:2)

您可以直接向api发出请求。

from urllib.request import urlopen
import json

def get_latest_commit(owner, repo):
    url = 'https://api.github.com/repos/{owner}/{repo}/commits?per_page=1'.format(owner=owner, repo=repo)
    response = urlopen(url).read()
    data = json.loads(response.decode())
    return data[0]

if __name__ == '__main__':
    commit = get_latest_commit('mycompany', 'therepo')
    print(commit['html_url'])

在这种情况下,您只会向api而不是3发出一个请求,而您只获得最后一次提交而不是所有提交。也应该更快。