-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_http.py
More file actions
224 lines (185 loc) · 6.68 KB
/
_http.py
File metadata and controls
224 lines (185 loc) · 6.68 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
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
from __future__ import annotations
import logging
import platform
import time
from datetime import datetime
from typing import Any
import httpx
from ._errors import PosthookConnectionError, PosthookError, _create_error
from ._models import QuotaInfo
from ._version import VERSION
logger = logging.getLogger("posthook")
DEFAULT_BASE_URL = "https://api.posthook.io"
DEFAULT_TIMEOUT = 30.0
def _parse_quota(headers: httpx.Headers) -> QuotaInfo | None:
limit = headers.get("posthook-hookquota-limit")
if not limit:
return None
resets_at: datetime | None = None
raw_resets = headers.get("posthook-hookquota-resets-at", "")
if raw_resets:
try:
resets_at = datetime.fromisoformat(raw_resets.replace("Z", "+00:00"))
except ValueError:
pass
return QuotaInfo(
limit=int(limit),
usage=int(headers.get("posthook-hookquota-usage", "0")),
remaining=int(headers.get("posthook-hookquota-remaining", "0")),
resets_at=resets_at,
)
_USER_AGENT = (
f"posthook-python/{VERSION}"
f" (Python {platform.python_version()}; {platform.system()})"
)
def _headers(api_key: str) -> dict[str, str]:
return {
"X-API-Key": api_key,
"User-Agent": _USER_AGENT,
"Content-Type": "application/json",
}
def _unwrap_data(body: dict[str, Any]) -> Any:
"""Extract 'data' from the API response envelope."""
return body.get("data")
def _extract_error_message(response: httpx.Response) -> str:
try:
body = response.json()
return body.get("error", f"HTTP {response.status_code}")
except Exception:
return f"HTTP {response.status_code}"
class SyncHttpClient:
"""Synchronous HTTP client wrapping httpx.Client."""
def __init__(
self,
api_key: str,
*,
base_url: str = DEFAULT_BASE_URL,
timeout: float = DEFAULT_TIMEOUT,
http_client: httpx.Client | None = None,
) -> None:
self._api_key = api_key
self._base_url = base_url.rstrip("/")
self._owns_client = http_client is None
self._client = http_client or httpx.Client(
timeout=timeout,
headers=_headers(api_key),
)
if http_client is not None:
self._client.headers.update(_headers(api_key))
def request(
self,
method: str,
path: str,
*,
json: Any = None,
params: dict[str, Any] | None = None,
timeout: float | None = None,
) -> tuple[Any, httpx.Headers]:
url = f"{self._base_url}{path}"
# Filter out None values from params
if params:
params = {k: v for k, v in params.items() if v is not None}
start = time.monotonic()
try:
kwargs: dict[str, Any] = {"json": json, "params": params}
if timeout is not None:
kwargs["timeout"] = timeout
response = self._client.request(
method, url, **kwargs
)
elapsed = time.monotonic() - start
logger.debug("%s %s -> %d (%.3fs)", method, path, response.status_code, elapsed)
if response.status_code >= 400:
msg = _extract_error_message(response)
hdrs = dict(response.headers)
raise _create_error(response.status_code, msg, hdrs)
body = response.json()
return body, response.headers
except PosthookError:
raise
except httpx.TimeoutException as exc:
raise PosthookConnectionError(f"Request timed out: {exc}") from exc
except httpx.HTTPError as exc:
raise PosthookConnectionError(f"Network error: {exc}") from exc
def request_data(
self,
method: str,
path: str,
*,
json: Any = None,
params: dict[str, Any] | None = None,
timeout: float | None = None,
) -> tuple[Any, httpx.Headers]:
"""Make a request and return (unwrapped_data, headers)."""
body, headers = self.request(method, path, json=json, params=params, timeout=timeout)
return _unwrap_data(body), headers
def close(self) -> None:
if self._owns_client:
self._client.close()
class AsyncHttpClient:
"""Asynchronous HTTP client wrapping httpx.AsyncClient."""
def __init__(
self,
api_key: str,
*,
base_url: str = DEFAULT_BASE_URL,
timeout: float = DEFAULT_TIMEOUT,
http_client: httpx.AsyncClient | None = None,
) -> None:
self._api_key = api_key
self._base_url = base_url.rstrip("/")
self._owns_client = http_client is None
self._client = http_client or httpx.AsyncClient(
timeout=timeout,
headers=_headers(api_key),
)
if http_client is not None:
self._client.headers.update(_headers(api_key))
async def request(
self,
method: str,
path: str,
*,
json: Any = None,
params: dict[str, Any] | None = None,
timeout: float | None = None,
) -> tuple[Any, httpx.Headers]:
url = f"{self._base_url}{path}"
if params:
params = {k: v for k, v in params.items() if v is not None}
start = time.monotonic()
try:
kwargs: dict[str, Any] = {"json": json, "params": params}
if timeout is not None:
kwargs["timeout"] = timeout
response = await self._client.request(
method, url, **kwargs
)
elapsed = time.monotonic() - start
logger.debug("%s %s -> %d (%.3fs)", method, path, response.status_code, elapsed)
if response.status_code >= 400:
msg = _extract_error_message(response)
hdrs = dict(response.headers)
raise _create_error(response.status_code, msg, hdrs)
body = response.json()
return body, response.headers
except PosthookError:
raise
except httpx.TimeoutException as exc:
raise PosthookConnectionError(f"Request timed out: {exc}") from exc
except httpx.HTTPError as exc:
raise PosthookConnectionError(f"Network error: {exc}") from exc
async def request_data(
self,
method: str,
path: str,
*,
json: Any = None,
params: dict[str, Any] | None = None,
timeout: float | None = None,
) -> tuple[Any, httpx.Headers]:
body, headers = await self.request(method, path, json=json, params=params, timeout=timeout)
return _unwrap_data(body), headers
async def close(self) -> None:
if self._owns_client:
await self._client.aclose()