2

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?

Chris Redford
  • 16,982
  • 21
  • 89
  • 109

2 Answers2

4

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
Chris Redford
  • 16,982
  • 21
  • 89
  • 109
2

You could directly make a request to the 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'])

In this case you would only being making one request to the api instead of 3 and you are only getting the last commit instead of all of them. Should be faster as well.

Tim Martin
  • 2,419
  • 1
  • 21
  • 25