2

我正在使用此函数使用PyGithub获取最新的提交 url :

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 地址不满意,并且对生成的 url 响应缓慢。我有没有更有效的方法来做到这一点?

4

2 回答 2

4

如果您在过去 24 小时内没有提交,这将不起作用。但是根据Github API 文档,如果你这样做,它似乎会更快地返回并且请求更少的提交:

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
于 2015-04-20T22:56:26.847 回答
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 个请求,并且您只会获得最后一次提交而不是所有提交。也应该更快。

于 2015-04-20T23:09:47.693 回答