Search code examples
pythongitgithubpygithub

Get Latest Commit URL from PyGithub Efficiently


I'm using this function to get the latest commit url using 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

It works but it seems to make Github unhappy with my IP address and give me a slow response for the resulting url. Is there a more efficient way for me to do this?


Solution

  • This wouldn't work if you had no commits in the past 24 hours. But if you do, it seems to return faster and will request fewer commits, according to the 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