Skip to content

Instantly share code, notes, and snippets.

@pmallory
Last active March 18, 2016 23:47
Show Gist options
  • Save pmallory/81b1bac2b4ea7a18034b to your computer and use it in GitHub Desktop.
Save pmallory/81b1bac2b4ea7a18034b to your computer and use it in GitHub Desktop.
A class that demonstrates the iterable interface and generator functions.
import math
import requests
class GitHubRepo:
"""
A demonstration of iterables.
You can iterate over the commits made to a GitHub repo by iterating over
an instance of this class.
Warning! This is only a demonstration, this code shouldn't be
used in production environments :)
"""
def __init__(self, owner, repo_name):
self.owner = owner
self.repo = repo_name
def __iter__(self, page_limit=2):
"""
Generates the 60 most recent commits by default (30 commits per page,
default page_limit of 2).
Set limit to None to fetch all commits. Don't violate GitHub's rate
limits!
https://developer.github.com/v3/#rate-limiting
"""
if not page_limit:
page_limit = math.inf
for page_number in range(page_limit):
commits = self.get_commits(page_number)
#If there are no more commits, stop sending requests
if len(commits) is 0:
break
for commit in commits:
yield commit
def get_commits(self, page_number):
"""
Fetch a list of commits from the repo. Results are paginated started.
from 0, increase this to get older commits.
Returns a list of dicts, each dict represents a commit. The structure
of the data structure is explained at
https://developer.github.com/v3/repos/commits/
"""
url = "https://api.github.com/repos/{}/{}/commits".format(self.owner,
self.repo)
response = requests.get(url, params={"page":page_number})
assert response.status_code is 200
return response.json()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment