Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2@file
3@brief Calls :epkg:`github` API.
4"""
5import requests
8class GitHubApiException(Exception):
9 """
10 Exception raised when a call to github rest api failed.
11 """
13 def __init__(self, response, url, **kwargs):
14 """
15 Merges everything into a string.
16 """
17 msg = ['%s=%r' % (k, v) for k, v in sorted(kwargs.items())]
18 if msg:
19 msg = "\n" + "\n".join(msg)
20 Exception.__init__(
21 self,
22 "response={0}\nurl='{1}'\ntext='{2}'\nstatus={3}{4}".format(
23 response, url, response.text, response.status_code, msg))
26def call_github_api(owner, repo, ask, auth=None, headers=None):
27 """
28 Calls `GitHub REST API <https://developer.github.com/v3/>`_.
30 @param owner owner of the project
31 @param auth tuple *(user, password)*
32 @param repo repository name
33 @param ask query (see below)
34 @param header dictionary
35 @return json
37 Example for *ask*:
39 * ``commits``
40 * ``downloads``
41 * ``forks``
42 * ``issues``
43 * ``pulls``
44 * ``stats/code_frequency`` - Needs authentification
45 * ``stats/commit_activity`` - Needs authentification
46 * ``stats/punch_card`` - Needs authentification
47 * ``traffic/popular/referrers`` - Must have push access to repository
48 * ``traffic/popular/paths`` - Must have push access to repository
49 * ``traffic/views`` - Must have push access to repository
50 * ``traffic/clones`` - Must have push access to repository
52 GitHub limits the number of requets per hour:
53 `Rate Limiting <https://developer.github.com/v3/#rate-limiting>`_.
54 """
55 url = 'https://api.github.com/repos/{0}/{1}/{2}'.format(
56 owner, repo, ask.strip('/'))
57 if '...' in url:
58 raise ValueError(
59 "Unexpected url=%r, owner=%r, auth=%r, repo=%r." % (
60 url, owner, auth, repo))
61 response = requests.get(url, auth=auth, headers=headers)
62 if response.status_code != 200:
63 raise GitHubApiException(response, url, owner=owner, repo=repo,
64 ask=ask, auth=auth)
65 return response.json()