|
23 | 23 | class AsyncGitHubClient(object):
|
24 | 24 | """AsyncHTTPClient wrapper with methods for common requests"""
|
25 | 25 | auth = None
|
26 |
| - |
| 26 | + |
27 | 27 | def __init__(self, client=None):
|
28 | 28 | self.client = client or AsyncHTTPClient()
|
29 | 29 | self.github_api_url = os.environ.get('GITHUB_API_URL', 'https://api.github.com/')
|
30 | 30 | self.authenticate()
|
31 |
| - |
| 31 | + |
32 | 32 | def authenticate(self):
|
33 | 33 | self.auth = {
|
34 | 34 | 'client_id': os.environ.get('GITHUB_OAUTH_KEY', ''),
|
35 | 35 | 'client_secret': os.environ.get('GITHUB_OAUTH_SECRET', ''),
|
36 |
| - 'access_token' : os.environ.get('GITHUB_API_TOKEN', ''), |
| 36 | + 'access_token': os.environ.get('GITHUB_API_TOKEN', ''), |
37 | 37 | }
|
38 |
| - self.auth = {k:v for k,v in self.auth.items() if v} |
39 |
| - |
| 38 | + |
40 | 39 | def fetch(self, url, callback=None, params=None, **kwargs):
|
41 | 40 | """Add GitHub auth to self.client.fetch"""
|
42 |
| - host = urlparse(url).hostname |
43 |
| - |
44 | 41 | if not url.startswith(self.github_api_url):
|
45 | 42 | raise ValueError(
|
46 | 43 | "Only fetch GitHub urls with GitHub auth (%s)" % url
|
47 | 44 | )
|
48 | 45 | params = {} if params is None else params
|
49 | 46 | kwargs.setdefault('user_agent', 'Tornado-Async-GitHub-Client')
|
50 |
| - if self.auth: |
51 |
| - params.update(self.auth) |
| 47 | + |
| 48 | + if self.auth['client_id'] and self.auth['client_secret']: |
| 49 | + kwargs['auth_username'] = self.auth['client_id'] |
| 50 | + kwargs['auth_password'] = self.auth['client_secret'] |
| 51 | + |
| 52 | + if self.auth['access_token']: |
| 53 | + headers = kwargs.setdefault('headers', {}) |
| 54 | + headers['Authorization'] = 'token ' + self.auth['access_token'] |
| 55 | + |
52 | 56 | url = url_concat(url, params)
|
53 | 57 | future = self.client.fetch(url, callback, **kwargs)
|
54 | 58 | future.add_done_callback(self._log_rate_limit)
|
55 | 59 | return future
|
56 |
| - |
| 60 | + |
57 | 61 | def _log_rate_limit(self, future):
|
58 | 62 | """log GitHub rate limit headers
|
59 |
| - |
| 63 | +
|
60 | 64 | - error if 0 remaining
|
61 | 65 | - warn if 10% or less remain
|
62 | 66 | - debug otherwise
|
|
0 commit comments