-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_client.py
More file actions
118 lines (86 loc) · 2.8 KB
/
github_client.py
File metadata and controls
118 lines (86 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# -*- coding: utf-8 -*-
from __future__ import annotations
import httpx
TIMEOUT = 60
BASE_URL = 'https://api.github.com'
class _Executable:
def __init__(self, _gh: GitHub, _method: str, _path: str):
self._gh = _gh
self._method = _method
self._path = _path
def __call__(self, **kw):
return self._gh._http(self._method, self._path, **kw)
# sdfs
class _Callable:
def __init__(self, _gh, _name):
self._gh = _gh
self._name = _name
def __call__(self, *args):
if len(args) == 0:
return self
name = f'{self._name}/{"/".join([str(arg) for arg in args])}'
return _Callable(self._gh, name)
def __getattr__(self, attr):
if attr in ['get', 'put', 'post', 'patch', 'delete']:
return _Executable(self._gh, attr, self._name)
name = f'{self._name}/{attr}'
return _Callable(self._gh, name)
class GitHub:
"""
GitHub client.
"""
def __init__(self, session: httpx.Client):
self.session = session
def __getattr__(self, attr):
return _Callable(self, f'/{attr}')
def _http(self, method: str, path: str, *, use_bytes: bool = False, use_text: bool = False, **kw):
_method = method.lower()
requests_kwargs = {}
headers = kw.pop('headers', {})
if _method == 'get' and kw:
requests_kwargs = {'params': kw}
elif _method in ['post', 'patch', 'put']:
requests_kwargs = {'json': kw}
response = self.session.request(
_method.upper(),
path,
timeout=TIMEOUT,
headers=headers,
**requests_kwargs,
)
if use_bytes:
contents = response.content
elif use_text:
contents = response.text
else:
contents = response_contents(response)
try:
response.raise_for_status()
except httpx.HTTPStatusError as exc:
cls: type[ApiError] = {
403: Forbidden,
404: NotFound,
}.get(exc.response.status_code, ApiError)
raise cls(str(contents)) from exc
return contents
def response_contents(
response: httpx.Response,
) -> JsonObject | bytes:
if response.headers.get('content-type', '').startswith('application/json'):
return response.json(object_hook=JsonObject)
return response.content
class JsonObject(dict):
"""
general json object that can bind any fields but also act as a dict.
"""
def __getattr__(self, key):
try:
return self[key]
except KeyError as e:
raise AttributeError(f"'Dict' object has no attribute '{key}'") from e
class ApiError(Exception):
pass
class NotFound(ApiError):
pass
class Forbidden(ApiError):
pass