-
-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathclient.py
247 lines (213 loc) · 7.63 KB
/
client.py
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
"""Synchronous and asynchronous clients for Notion's API."""
import json
import logging
from abc import abstractmethod
from dataclasses import dataclass
from types import TracebackType
from typing import Any, Dict, List, Generic, Optional, Type, Union
import httpx
from httpx import Request, Response
from notion_client.api_endpoints import (
BlocksEndpoint,
CommentsEndpoint,
DatabasesEndpoint,
PagesEndpoint,
SearchEndpoint,
UsersEndpoint,
)
from notion_client.errors import (
APIResponseError,
HTTPResponseError,
RequestTimeoutError,
is_api_error_code,
)
from notion_client.logging import make_console_logger
from notion_client.typing import ClientType, ResponseType, SyncAsync
@dataclass
class ClientOptions:
"""Options to configure the client.
Attributes:
auth: Bearer token for authentication. If left undefined, the `auth` parameter
should be set on each request.
timeout_ms: Number of milliseconds to wait before emitting a
`RequestTimeoutError`.
base_url: The root URL for sending API requests. This can be changed to test with
a mock server.
log_level: Verbosity of logs the instance will produce. By default, logs are
written to `stdout`.
logger: A custom logger.
notion_version: Notion version to use.
"""
auth: Optional[str] = None
timeout_ms: int = 60_000
base_url: str = "https://api.notion.com"
log_level: int = logging.WARNING
logger: Optional[logging.Logger] = None
notion_version: str = "2022-06-28"
class BaseClient(Generic[ClientType]):
def __init__(
self,
client: Union[httpx.Client, httpx.AsyncClient],
options: Optional[Union[Dict[str, Any], ClientOptions]] = None,
**kwargs: Any,
) -> None:
if options is None:
options = ClientOptions(**kwargs)
elif isinstance(options, dict):
options = ClientOptions(**options)
self.logger = options.logger or make_console_logger()
self.logger.setLevel(options.log_level)
self.options = options
self._clients: List[Union[httpx.Client, httpx.AsyncClient]] = []
self.client = client
self.blocks = BlocksEndpoint[ClientType](self)
self.databases = DatabasesEndpoint[ClientType](self)
self.users = UsersEndpoint[ClientType](self)
self.pages = PagesEndpoint[ClientType](self)
self.search = SearchEndpoint[ClientType](self)
self.comments = CommentsEndpoint[ClientType](self)
@property
def client(self) -> Union[httpx.Client, httpx.AsyncClient]:
return self._clients[-1]
@client.setter
def client(self, client: Union[httpx.Client, httpx.AsyncClient]) -> None:
client.base_url = httpx.URL(f"{self.options.base_url}/v1/")
client.timeout = httpx.Timeout(timeout=self.options.timeout_ms / 1_000)
client.headers = httpx.Headers(
{
"Notion-Version": self.options.notion_version,
"User-Agent": "ramnes/[email protected]",
}
)
if self.options.auth:
client.headers["Authorization"] = f"Bearer {self.options.auth}"
self._clients.append(client)
def _build_request(
self,
method: str,
path: str,
query: Optional[Dict[Any, Any]] = None,
body: Optional[Dict[Any, Any]] = None,
auth: Optional[str] = None,
) -> Request:
headers = httpx.Headers()
if auth:
headers["Authorization"] = f"Bearer {auth}"
self.logger.info(f"{method} {self.client.base_url}{path}")
self.logger.debug(f"=> {query} -- {body}")
return self.client.build_request(
method, path, params=query, json=body, headers=headers
)
def _parse_response(self, response: Response) -> Any:
try:
response.raise_for_status()
except httpx.HTTPStatusError as error:
try:
body = error.response.json()
code = body.get("code")
except json.JSONDecodeError:
code = None
if code and is_api_error_code(code):
raise APIResponseError(response, body["message"], code)
raise HTTPResponseError(error.response)
body = response.json()
self.logger.debug(f"=> {body}")
return body
@abstractmethod
def request(
self,
path: str,
method: str,
cast_to: Type[ResponseType],
query: Optional[Dict[Any, Any]] = None,
body: Optional[Dict[Any, Any]] = None,
auth: Optional[str] = None,
) -> SyncAsync[ResponseType]:
# noqa
pass
class Client(BaseClient):
"""Synchronous client for Notion's API."""
client: httpx.Client
def __init__(
self,
options: Optional[Union[Dict[Any, Any], ClientOptions]] = None,
client: Optional[httpx.Client] = None,
**kwargs: Any,
) -> None:
if client is None:
client = httpx.Client()
super().__init__(client, options, **kwargs)
def __enter__(self) -> "Client":
self.client = httpx.Client()
self.client.__enter__()
return self
def __exit__(
self,
exc_type: Type[BaseException],
exc_value: BaseException,
traceback: TracebackType,
) -> None:
self.client.__exit__(exc_type, exc_value, traceback)
del self._clients[-1]
def close(self) -> None:
"""Close the connection pool of the current inner client."""
self.client.close()
def request(
self,
path: str,
method: str,
cast_to: Type[ResponseType],
query: Optional[Dict[Any, Any]] = None,
body: Optional[Dict[Any, Any]] = None,
auth: Optional[str] = None,
) -> ResponseType:
"""Send an HTTP request."""
request = self._build_request(method, path, query, body, auth)
try:
response = self.client.send(request)
except httpx.TimeoutException:
raise RequestTimeoutError()
return cast_to(self._parse_response(response))
class AsyncClient(BaseClient):
"""Asynchronous client for Notion's API."""
client: httpx.AsyncClient
def __init__(
self,
options: Optional[Union[Dict[str, Any], ClientOptions]] = None,
client: Optional[httpx.AsyncClient] = None,
**kwargs: Any,
) -> None:
if client is None:
client = httpx.AsyncClient()
super().__init__(client, options, **kwargs)
async def __aenter__(self) -> "AsyncClient":
self.client = httpx.AsyncClient()
await self.client.__aenter__()
return self
async def __aexit__(
self,
exc_type: Type[BaseException],
exc_value: BaseException,
traceback: TracebackType,
) -> None:
await self.client.__aexit__(exc_type, exc_value, traceback)
del self._clients[-1]
async def aclose(self) -> None:
"""Close the connection pool of the current inner client."""
await self.client.aclose()
async def request(
self,
path: str,
method: str,
cast_to: Type[ResponseType],
query: Optional[Dict[Any, Any]] = None,
body: Optional[Dict[Any, Any]] = None,
auth: Optional[str] = None,
) -> ResponseType:
"""Send an HTTP request asynchronously."""
request = self._build_request(method, path, query, body, auth)
try:
response = await self.client.send(request)
except httpx.TimeoutException:
raise RequestTimeoutError()
return cast_to(self._parse_response(response))