-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathgithub_client.py
More file actions
135 lines (99 loc) · 3.14 KB
/
github_client.py
File metadata and controls
135 lines (99 loc) · 3.14 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#!/usr/bin/env python
"""
From: https://github.com/michaelliao/githubpy/blob/96d0c3e729c0b3e3c043a604547ccff17782ac2b/github.py
GitHub API Python SDK. (Python >= 2.6)
Apache License
Michael Liao (askxuefeng@gmail.com)
License: https://github.com/michaelliao/githubpy/blob/96d0c3e729c0b3e3c043a604547ccff17782ac2b/LICENSE.txt
"""
from __future__ import annotations
__version__ = "1.1.1"
import httpx
TIMEOUT = 60
_URL = "https://api.github.com"
class _Executable:
def __init__(self, _gh, _method, _path):
self._gh = _gh
self._method = _method
self._path = _path
def __call__(self, **kw):
return self._gh._http(self._method, self._path, **kw)
class _Callable:
def __init__(self, _gh, _name):
self._gh = _gh
self._name = _name
def __call__(self, *args):
if len(args) == 0:
return self
name = "{}/{}".format(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,
*,
bytes: bool = False,
headers: dict[str, str] | None = None,
**kw,
):
_method = method.lower()
requests_kwargs = {}
header_kwargs = {"headers": headers} if headers else {}
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,
**header_kwargs,
**requests_kwargs,
)
contents = response_contents(response=response, bytes=bytes)
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,
bytes: bool,
) -> JsonObject | str | bytes:
if bytes:
return response.content
if response.headers.get("content-type", "").startswith("application/json"):
return response.json(object_hook=JsonObject)
return response.text
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:
raise AttributeError(rf"'Dict' object has no attribute '{key}'")
class ApiError(Exception):
pass
class NotFound(ApiError):
pass
class Forbidden(ApiError):
pass