polite-http 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- polite_http/__init__.py +49 -0
- polite_http/http_client.py +924 -0
- polite_http/py.typed +0 -0
- polite_http-0.1.0.dist-info/METADATA +156 -0
- polite_http-0.1.0.dist-info/RECORD +8 -0
- polite_http-0.1.0.dist-info/WHEEL +4 -0
- polite_http-0.1.0.dist-info/licenses/LICENSE +202 -0
- polite_http-0.1.0.dist-info/licenses/NOTICE +27 -0
polite_http/__init__.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# Copyright 2026 polite-http contributors
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""polite-http — a courteous, dependency-free HTTP client.
|
|
16
|
+
|
|
17
|
+
Rate limiting, automatic retries, exponential backoff with jitter,
|
|
18
|
+
`Retry-After` support, and proactive `X-Throttling-Control` backpressure —
|
|
19
|
+
built entirely on the Python standard library.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from polite_http.http_client import (
|
|
23
|
+
DEFAULT_BACKOFF_BASE_SECS,
|
|
24
|
+
DEFAULT_BACKOFF_MAX_SECS,
|
|
25
|
+
DEFAULT_JITTER_SECS,
|
|
26
|
+
DEFAULT_MAX_RETRIES,
|
|
27
|
+
DEFAULT_TIMEOUT_SECS,
|
|
28
|
+
RETRYABLE_STATUS_CODES,
|
|
29
|
+
USER_AGENT_ENV_VAR,
|
|
30
|
+
HttpClient,
|
|
31
|
+
HttpError,
|
|
32
|
+
HttpResponse,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
__version__ = "0.1.0"
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"HttpClient",
|
|
39
|
+
"HttpError",
|
|
40
|
+
"HttpResponse",
|
|
41
|
+
"DEFAULT_BACKOFF_BASE_SECS",
|
|
42
|
+
"DEFAULT_BACKOFF_MAX_SECS",
|
|
43
|
+
"DEFAULT_JITTER_SECS",
|
|
44
|
+
"DEFAULT_MAX_RETRIES",
|
|
45
|
+
"DEFAULT_TIMEOUT_SECS",
|
|
46
|
+
"RETRYABLE_STATUS_CODES",
|
|
47
|
+
"USER_AGENT_ENV_VAR",
|
|
48
|
+
"__version__",
|
|
49
|
+
]
|
|
@@ -0,0 +1,924 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
# Copyright 2026 polite-http contributors
|
|
3
|
+
#
|
|
4
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
# you may not use this file except in compliance with the License.
|
|
6
|
+
# You may obtain a copy of the License at
|
|
7
|
+
#
|
|
8
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
#
|
|
10
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
# See the License for the specific language governing permissions and
|
|
14
|
+
# limitations under the License.
|
|
15
|
+
#
|
|
16
|
+
# This file is derived from `http_client.py` in google-deepmind/science-skills
|
|
17
|
+
# (https://github.com/google-deepmind/science-skills). See the NOTICE file in
|
|
18
|
+
# the project root for a description of the modifications.
|
|
19
|
+
|
|
20
|
+
"""Unified HTTP client with rate limiting, retries, and backoff.
|
|
21
|
+
|
|
22
|
+
Provides `HttpClient` — a single entry-point that combines:
|
|
23
|
+
|
|
24
|
+
* **Per-host rate limiting** via `_RateLimiter` (cross-process file-lock).
|
|
25
|
+
* **Automatic retries** on transient errors (HTTP 429, 5xx).
|
|
26
|
+
* **Exponential backoff** with optional *jitter*.
|
|
27
|
+
* **Retry-After header** support (server-directed backoff).
|
|
28
|
+
* **X-Throttling-Control** proactive backpressure (PubChem / NCBI).
|
|
29
|
+
* **Configurable timeouts** per request.
|
|
30
|
+
|
|
31
|
+
Transport is `urllib.request` (stdlib) — no third-party dependencies.
|
|
32
|
+
|
|
33
|
+
Typical usage:
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from polite_http import HttpClient
|
|
37
|
+
|
|
38
|
+
# Scoped to a specific base URL.
|
|
39
|
+
api_client = HttpClient(
|
|
40
|
+
"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/",
|
|
41
|
+
qps=3,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
# Simple GET with relative path (returns parsed JSON).
|
|
45
|
+
data = api_client.fetch_json("esummary.fcgi?db=pubmed&id=123456")
|
|
46
|
+
|
|
47
|
+
# POST with a JSON body.
|
|
48
|
+
data = api_client.fetch_json(
|
|
49
|
+
"esearch.fcgi",
|
|
50
|
+
method="POST",
|
|
51
|
+
json_body={"db": "pubmed", "term": "cancer"},
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
# Raw bytes (e.g. file / PDF download).
|
|
55
|
+
pdf = api_client.fetch_bytes(
|
|
56
|
+
"efetch.fcgi?db=pubmed&id=123456&rettype=abstract",
|
|
57
|
+
timeout=60,
|
|
58
|
+
)
|
|
59
|
+
```
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
from __future__ import annotations
|
|
63
|
+
|
|
64
|
+
import contextlib
|
|
65
|
+
import datetime
|
|
66
|
+
import email.utils
|
|
67
|
+
import gzip
|
|
68
|
+
import http.client
|
|
69
|
+
import json
|
|
70
|
+
import logging
|
|
71
|
+
import os
|
|
72
|
+
import random
|
|
73
|
+
import re
|
|
74
|
+
import sys
|
|
75
|
+
import time
|
|
76
|
+
import urllib.error
|
|
77
|
+
import urllib.parse
|
|
78
|
+
import urllib.request
|
|
79
|
+
from collections.abc import Iterator
|
|
80
|
+
from typing import Any
|
|
81
|
+
|
|
82
|
+
# Cross-process exclusive file locking, implemented on the standard library
|
|
83
|
+
# only. POSIX uses ``fcntl.flock``; Windows uses ``msvcrt.locking`` (byte-range
|
|
84
|
+
# lock). If neither is available (rare sandboxed runtimes), the limiter falls
|
|
85
|
+
# back to a best-effort in-process timer.
|
|
86
|
+
if sys.platform == "win32": # pragma: no cover - exercised only on Windows
|
|
87
|
+
import msvcrt
|
|
88
|
+
|
|
89
|
+
def _lock(f) -> None:
|
|
90
|
+
# Lock one byte at offset 0 as a whole-file mutex. ``LK_LOCK`` blocks,
|
|
91
|
+
# retrying for ~10s per call before raising, so loop until acquired.
|
|
92
|
+
f.seek(0)
|
|
93
|
+
while True:
|
|
94
|
+
try:
|
|
95
|
+
msvcrt.locking(f.fileno(), msvcrt.LK_LOCK, 1)
|
|
96
|
+
return
|
|
97
|
+
except OSError:
|
|
98
|
+
continue
|
|
99
|
+
|
|
100
|
+
def _unlock(f) -> None:
|
|
101
|
+
f.seek(0)
|
|
102
|
+
msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1)
|
|
103
|
+
|
|
104
|
+
_HAS_FILE_LOCK = True
|
|
105
|
+
else:
|
|
106
|
+
try:
|
|
107
|
+
import fcntl
|
|
108
|
+
|
|
109
|
+
def _lock(f) -> None:
|
|
110
|
+
fcntl.flock(f, fcntl.LOCK_EX)
|
|
111
|
+
|
|
112
|
+
def _unlock(f) -> None:
|
|
113
|
+
fcntl.flock(f, fcntl.LOCK_UN)
|
|
114
|
+
|
|
115
|
+
_HAS_FILE_LOCK = True
|
|
116
|
+
except ImportError: # pragma: no cover - rare sandboxed runtimes
|
|
117
|
+
_HAS_FILE_LOCK = False
|
|
118
|
+
|
|
119
|
+
__all__ = [
|
|
120
|
+
"HttpClient",
|
|
121
|
+
"HttpError",
|
|
122
|
+
"HttpResponse",
|
|
123
|
+
"DEFAULT_BACKOFF_BASE_SECS",
|
|
124
|
+
"DEFAULT_BACKOFF_MAX_SECS",
|
|
125
|
+
"DEFAULT_JITTER_SECS",
|
|
126
|
+
"DEFAULT_MAX_RETRIES",
|
|
127
|
+
"DEFAULT_TIMEOUT_SECS",
|
|
128
|
+
"RETRYABLE_STATUS_CODES",
|
|
129
|
+
"USER_AGENT_ENV_VAR",
|
|
130
|
+
]
|
|
131
|
+
|
|
132
|
+
RETRYABLE_STATUS_CODES: frozenset[int] = frozenset({429, 500, 502, 503, 504})
|
|
133
|
+
DEFAULT_TIMEOUT_SECS: float = 60.0
|
|
134
|
+
DEFAULT_MAX_RETRIES: int = 7
|
|
135
|
+
DEFAULT_BACKOFF_BASE_SECS: float = 3.0
|
|
136
|
+
DEFAULT_BACKOFF_MAX_SECS: float = 180.0
|
|
137
|
+
DEFAULT_JITTER_SECS: float = 0.5
|
|
138
|
+
DEFAULT_CHARSET: str = "utf-8"
|
|
139
|
+
PROJECT_NAME: str = "polite-http"
|
|
140
|
+
USER_AGENT_ENV_VAR: str = "POLITE_HTTP_USER_AGENT"
|
|
141
|
+
|
|
142
|
+
# Regex for parsing X-Throttling-Control status entries.
|
|
143
|
+
# Matches e.g. "Request Count status: Red (82%)".
|
|
144
|
+
_THROTTLE_STATUS_RE = re.compile(
|
|
145
|
+
r"(\w[\w ]*?) status:\s*(Green|Yellow|Red|Black)\s*\((\d+)%\)"
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
# Backpressure delays (seconds) keyed by throttle colour.
|
|
149
|
+
_THROTTLE_BACKPRESSURE: dict[str, float] = {
|
|
150
|
+
"Green": 0.0,
|
|
151
|
+
"Yellow": 1.0,
|
|
152
|
+
"Red": 5.0,
|
|
153
|
+
"Black": 30.0,
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class _RateLimiter:
|
|
158
|
+
"""Enforces a minimum interval between requests.
|
|
159
|
+
|
|
160
|
+
Uses a shared lock file so multiple processes respect the same rate limit
|
|
161
|
+
(the lock file path is derived from the hostname, e.g.
|
|
162
|
+
``/tmp/polite-http-ncbi.nlm.nih.gov.lock``). The cross-process lock works
|
|
163
|
+
on POSIX (``fcntl``) and Windows (``msvcrt``). On the rare platform that
|
|
164
|
+
provides neither, it falls back to a best-effort, in-process timer.
|
|
165
|
+
|
|
166
|
+
The shared timestamp is `time.monotonic()`, whose clock is system-wide on
|
|
167
|
+
every supported platform, so the value is comparable across processes on
|
|
168
|
+
the same host.
|
|
169
|
+
|
|
170
|
+
Example:
|
|
171
|
+
limiter = _RateLimiter('ncbi.nlm.nih.gov', qps=10)
|
|
172
|
+
"""
|
|
173
|
+
|
|
174
|
+
def __init__(self, hostname: str, qps: float):
|
|
175
|
+
"""Initialize rate limiter.
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
hostname: Hostname of the API.
|
|
179
|
+
qps: Maximum queries per second.
|
|
180
|
+
"""
|
|
181
|
+
if qps <= 0:
|
|
182
|
+
raise ValueError(f"qps must be positive, got {qps!r}")
|
|
183
|
+
self._min_interval = 1.0 / qps
|
|
184
|
+
self._lock_file = os.path.join(_lock_dir(), f"{PROJECT_NAME}-{hostname}.lock")
|
|
185
|
+
# Used only when no cross-process file lock is available.
|
|
186
|
+
self._last_ts = 0.0
|
|
187
|
+
|
|
188
|
+
def wait(self, min_sleep: float = 0.0):
|
|
189
|
+
"""Block until the next request is allowed.
|
|
190
|
+
|
|
191
|
+
Args:
|
|
192
|
+
min_sleep: Additional minimum sleep in seconds. The actual delay is
|
|
193
|
+
`max(rate_limit_gap, min_sleep)`, which lets callers fold retry back-off
|
|
194
|
+
into the same call.
|
|
195
|
+
"""
|
|
196
|
+
if not _HAS_FILE_LOCK: # pragma: no cover - rare sandboxed runtimes
|
|
197
|
+
now = time.monotonic()
|
|
198
|
+
gap = self._min_interval - (now - self._last_ts)
|
|
199
|
+
delay = max(gap, min_sleep)
|
|
200
|
+
if delay > 0:
|
|
201
|
+
time.sleep(delay)
|
|
202
|
+
self._last_ts = time.monotonic()
|
|
203
|
+
return
|
|
204
|
+
|
|
205
|
+
# Open read/write in binary mode (no append semantics) so the same
|
|
206
|
+
# seek/truncate/byte-lock logic behaves identically on POSIX and
|
|
207
|
+
# Windows. ``O_CREAT`` makes the first caller create the lock file.
|
|
208
|
+
fd = os.open(self._lock_file, os.O_RDWR | os.O_CREAT, 0o644)
|
|
209
|
+
with os.fdopen(fd, "r+b") as f:
|
|
210
|
+
_lock(f)
|
|
211
|
+
try:
|
|
212
|
+
f.seek(0)
|
|
213
|
+
content = f.read().strip()
|
|
214
|
+
last_ts = float(content) if content else 0.0
|
|
215
|
+
now = time.monotonic()
|
|
216
|
+
gap = self._min_interval - (now - last_ts)
|
|
217
|
+
delay = max(gap, min_sleep)
|
|
218
|
+
if delay > 0:
|
|
219
|
+
time.sleep(delay)
|
|
220
|
+
f.seek(0)
|
|
221
|
+
f.truncate()
|
|
222
|
+
f.write(str(time.monotonic()).encode("ascii"))
|
|
223
|
+
f.flush()
|
|
224
|
+
finally:
|
|
225
|
+
_unlock(f)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _lock_dir() -> str:
|
|
229
|
+
"""Return the directory used for cross-process rate-limit lock files."""
|
|
230
|
+
return os.environ.get("POLITE_HTTP_LOCK_DIR") or _default_tmp_dir()
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _default_tmp_dir() -> str:
|
|
234
|
+
import tempfile
|
|
235
|
+
|
|
236
|
+
return tempfile.gettempdir()
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _maybe_decompress(
|
|
240
|
+
response: http.client.HTTPResponse,
|
|
241
|
+
) -> http.client.HTTPResponse | gzip.GzipFile:
|
|
242
|
+
"""Wrap the response in a gzip decompressor if Content-Encoding says so.
|
|
243
|
+
|
|
244
|
+
Args:
|
|
245
|
+
response: The response to wrap. Must support .read() and .headers.
|
|
246
|
+
|
|
247
|
+
Returns:
|
|
248
|
+
A `GzipFile` wrapper if the response is gzip-encoded, otherwise the
|
|
249
|
+
original response unchanged.
|
|
250
|
+
"""
|
|
251
|
+
encoding = response.headers.get("Content-Encoding", "").lower()
|
|
252
|
+
if encoding in ("gzip", "x-gzip"):
|
|
253
|
+
return gzip.GzipFile(fileobj=response)
|
|
254
|
+
return response
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class HttpError(Exception):
|
|
258
|
+
"""Raised when an HTTP request fails with a non-retryable or exhausted error.
|
|
259
|
+
|
|
260
|
+
Attributes:
|
|
261
|
+
status_code: HTTP status code (`None` for network-level failures).
|
|
262
|
+
body: Raw error response body bytes, if available.
|
|
263
|
+
url: The URL that was requested.
|
|
264
|
+
"""
|
|
265
|
+
|
|
266
|
+
MAX_BODY_SUMMARY_LEN = 500
|
|
267
|
+
|
|
268
|
+
def __init__(
|
|
269
|
+
self,
|
|
270
|
+
message: str,
|
|
271
|
+
*,
|
|
272
|
+
status_code: int | None = None,
|
|
273
|
+
body: bytes | None = None,
|
|
274
|
+
url: str | None = None,
|
|
275
|
+
):
|
|
276
|
+
# Append server body to message to help callers debug any errors.
|
|
277
|
+
if summary := self._summarize_body(body):
|
|
278
|
+
message = f"{message}\nServer body: {summary}"
|
|
279
|
+
|
|
280
|
+
super().__init__(message)
|
|
281
|
+
self.status_code = status_code
|
|
282
|
+
self.body = body
|
|
283
|
+
self.url = url
|
|
284
|
+
|
|
285
|
+
def json(self) -> Any:
|
|
286
|
+
"""Attempt to parse the error body as JSON."""
|
|
287
|
+
# Let the JSON decode fail with JSONDecodeError if the body is empty.
|
|
288
|
+
body = self.body or b""
|
|
289
|
+
return json.loads(body.decode("utf-8"))
|
|
290
|
+
|
|
291
|
+
@classmethod
|
|
292
|
+
def _summarize_body(cls, body: bytes | None) -> str | None:
|
|
293
|
+
"""Return a short summary of the error body if available."""
|
|
294
|
+
if not body:
|
|
295
|
+
return None
|
|
296
|
+
if body.startswith(b"\x1f\x8b"): # Gzip encoding.
|
|
297
|
+
try:
|
|
298
|
+
body = gzip.decompress(body)
|
|
299
|
+
except gzip.BadGzipFile:
|
|
300
|
+
return None
|
|
301
|
+
|
|
302
|
+
decoded = body.decode("utf-8", errors="replace").strip()
|
|
303
|
+
if len(decoded) > cls.MAX_BODY_SUMMARY_LEN:
|
|
304
|
+
return decoded[: cls.MAX_BODY_SUMMARY_LEN] + "..."
|
|
305
|
+
return decoded
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
class HttpResponse:
|
|
309
|
+
"""Lightweight wrapper around an HTTP response.
|
|
310
|
+
|
|
311
|
+
Attributes:
|
|
312
|
+
data: Raw response body bytes (decompressed if the server sent
|
|
313
|
+
`Content-Encoding: gzip`).
|
|
314
|
+
status_code: HTTP status code.
|
|
315
|
+
headers: Response headers as a dict.
|
|
316
|
+
url: The final URL after any redirects.
|
|
317
|
+
encoding: Character encoding parsed from the `Content-Type` header. Falls
|
|
318
|
+
back to `"utf-8"` when absent.
|
|
319
|
+
"""
|
|
320
|
+
|
|
321
|
+
__slots__ = ("data", "status_code", "headers", "url", "encoding")
|
|
322
|
+
|
|
323
|
+
def __init__(
|
|
324
|
+
self,
|
|
325
|
+
data: bytes,
|
|
326
|
+
status_code: int,
|
|
327
|
+
headers: dict[str, str],
|
|
328
|
+
url: str,
|
|
329
|
+
encoding: str | None = None,
|
|
330
|
+
):
|
|
331
|
+
self.data = data
|
|
332
|
+
self.status_code = status_code
|
|
333
|
+
self.headers = headers
|
|
334
|
+
self.url = url
|
|
335
|
+
self.encoding = encoding or "utf-8"
|
|
336
|
+
|
|
337
|
+
def json(self) -> Any:
|
|
338
|
+
"""Parse the response body as JSON."""
|
|
339
|
+
return json.loads(self.data.decode(self.encoding))
|
|
340
|
+
|
|
341
|
+
@property
|
|
342
|
+
def text(self) -> str:
|
|
343
|
+
"""Decode the response body using the detected charset."""
|
|
344
|
+
return self.data.decode(self.encoding)
|
|
345
|
+
|
|
346
|
+
def __repr__(self) -> str:
|
|
347
|
+
return (
|
|
348
|
+
f"HttpResponse(status={self.status_code}, "
|
|
349
|
+
f"url={self.url!r}, size={len(self.data)})"
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _parse_retry_after(headers) -> float | None:
|
|
354
|
+
"""Extract `Retry-After` value from HTTP response headers.
|
|
355
|
+
|
|
356
|
+
Handles both formats defined in RFC 7231 §7.1.3:
|
|
357
|
+
|
|
358
|
+
* **delta-seconds** — `Retry-After: 120`
|
|
359
|
+
* **HTTP-date** — `Retry-After: Mon, 31 Mar 2026 15:10:00 GMT`
|
|
360
|
+
|
|
361
|
+
Args:
|
|
362
|
+
headers: Response headers (dict-like or `http.client.HTTPMessage`).
|
|
363
|
+
|
|
364
|
+
Returns:
|
|
365
|
+
Delay in seconds, or `None` if the header is absent or not parseable.
|
|
366
|
+
"""
|
|
367
|
+
value = headers.get("Retry-After")
|
|
368
|
+
if value is None:
|
|
369
|
+
return None
|
|
370
|
+
|
|
371
|
+
try:
|
|
372
|
+
return float(value)
|
|
373
|
+
except ValueError:
|
|
374
|
+
pass
|
|
375
|
+
|
|
376
|
+
try:
|
|
377
|
+
retry_dt = email.utils.parsedate_to_datetime(value)
|
|
378
|
+
delta = (
|
|
379
|
+
retry_dt - datetime.datetime.now(datetime.timezone.utc)
|
|
380
|
+
).total_seconds()
|
|
381
|
+
return max(0.0, delta)
|
|
382
|
+
except (TypeError, ValueError, OverflowError):
|
|
383
|
+
logging.warning("Failed to parse Retry-After header value: %r", value)
|
|
384
|
+
return None
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def _parse_throttle_control(headers) -> float:
|
|
388
|
+
"""Parse `X-Throttling-Control` header for proactive backpressure.
|
|
389
|
+
|
|
390
|
+
The header (used by PubChem / NCBI) reports real-time usage across three
|
|
391
|
+
dimensions:
|
|
392
|
+
|
|
393
|
+
X-Throttling-Control: Request Count status: Green (12%),
|
|
394
|
+
Request Time status: Yellow (55%), Service status: Green (8%)
|
|
395
|
+
|
|
396
|
+
Each dimension has a colour: Green (<50%), Yellow (50–75%), Red (>75%), Black
|
|
397
|
+
(blocked). We return the worst-case backpressure delay across all dimensions
|
|
398
|
+
so the client can slow down **before** hitting a hard 429/503.
|
|
399
|
+
|
|
400
|
+
Args:
|
|
401
|
+
headers: Mapping of response headers.
|
|
402
|
+
|
|
403
|
+
Returns:
|
|
404
|
+
Recommended additional delay in seconds (0.0 if Green or header
|
|
405
|
+
is absent).
|
|
406
|
+
"""
|
|
407
|
+
value = headers.get("X-Throttling-Control")
|
|
408
|
+
if not value:
|
|
409
|
+
return 0.0
|
|
410
|
+
|
|
411
|
+
max_delay = 0.0
|
|
412
|
+
for match in _THROTTLE_STATUS_RE.finditer(value):
|
|
413
|
+
colour = match.group(2)
|
|
414
|
+
delay = _THROTTLE_BACKPRESSURE.get(colour, 0.0)
|
|
415
|
+
if delay > max_delay:
|
|
416
|
+
max_delay = delay
|
|
417
|
+
return max_delay
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
class HttpClient:
|
|
421
|
+
"""Rate-limited HTTP client with automatic retries and backoff.
|
|
422
|
+
|
|
423
|
+
Uses `urllib.request` as the transport layer. Handles gzip decompression,
|
|
424
|
+
charset detection, and streaming iteration internally.
|
|
425
|
+
|
|
426
|
+
Example:
|
|
427
|
+
|
|
428
|
+
chembl_api = HttpClient(
|
|
429
|
+
"https://www.ebi.ac.uk/chembl/api/data/",
|
|
430
|
+
qps=5,
|
|
431
|
+
jitter=0.5,
|
|
432
|
+
)
|
|
433
|
+
data = chembl_api.fetch_json("molecule/CHEMBL25.json")
|
|
434
|
+
"""
|
|
435
|
+
|
|
436
|
+
def __init__(
|
|
437
|
+
self,
|
|
438
|
+
base_url: str,
|
|
439
|
+
qps: float,
|
|
440
|
+
*,
|
|
441
|
+
default_headers: dict[str, str] | None = None,
|
|
442
|
+
max_retries: int = DEFAULT_MAX_RETRIES,
|
|
443
|
+
timeout: float = DEFAULT_TIMEOUT_SECS,
|
|
444
|
+
backoff_base: float = DEFAULT_BACKOFF_BASE_SECS,
|
|
445
|
+
backoff_max: float = DEFAULT_BACKOFF_MAX_SECS,
|
|
446
|
+
jitter: float = DEFAULT_JITTER_SECS,
|
|
447
|
+
user_agent: str | None = None,
|
|
448
|
+
retryable_status_codes: frozenset[int] = RETRYABLE_STATUS_CODES,
|
|
449
|
+
referer: str | None = None,
|
|
450
|
+
):
|
|
451
|
+
"""Rate-limited HTTP client with automatic retries and backoff.
|
|
452
|
+
|
|
453
|
+
Args:
|
|
454
|
+
base_url: Base URL of the API (e.g. "https://eutils.ncbi.nlm.nih.gov/").
|
|
455
|
+
qps: Maximum queries per second (steady-state).
|
|
456
|
+
default_headers: Default HTTP headers to include in every request.
|
|
457
|
+
max_retries: Maximum retry attempts for transient errors. The total
|
|
458
|
+
number of attempts is `max_retries + 1`.
|
|
459
|
+
timeout: Default per-request timeout in seconds.
|
|
460
|
+
backoff_base: Base delay (seconds) for exponential backoff.
|
|
461
|
+
backoff_max: Cap on backoff delay (seconds).
|
|
462
|
+
jitter: Maximum random jitter (seconds) added uniformly to each backoff
|
|
463
|
+
delay.
|
|
464
|
+
user_agent: Default `User-Agent` header value. Falls back to the
|
|
465
|
+
`POLITE_HTTP_USER_AGENT` env var.
|
|
466
|
+
retryable_status_codes: HTTP status codes that trigger a retry.
|
|
467
|
+
referer: Optional value for the HTTP `Referer` header sent with every
|
|
468
|
+
request.
|
|
469
|
+
"""
|
|
470
|
+
self.base_url = base_url
|
|
471
|
+
parsed = urllib.parse.urlparse(base_url)
|
|
472
|
+
if not parsed.scheme or not parsed.netloc or not parsed.hostname:
|
|
473
|
+
raise ValueError(f"base_url must be an absolute URL: {base_url!r}")
|
|
474
|
+
self.hostname: str = parsed.hostname
|
|
475
|
+
self.max_retries = max_retries
|
|
476
|
+
self.timeout = timeout
|
|
477
|
+
self.backoff_base = backoff_base
|
|
478
|
+
self.backoff_max = backoff_max
|
|
479
|
+
self.jitter = jitter
|
|
480
|
+
self.user_agent = user_agent or os.environ.get(USER_AGENT_ENV_VAR, "")
|
|
481
|
+
self.retryable_status_codes = retryable_status_codes
|
|
482
|
+
self.default_headers = default_headers or {}
|
|
483
|
+
self._limiter = _RateLimiter(self.hostname, qps=qps)
|
|
484
|
+
self._next_min_sleep = 0.0
|
|
485
|
+
self._referer = referer
|
|
486
|
+
|
|
487
|
+
def wait(self, min_sleep: float = 0.0) -> None:
|
|
488
|
+
"""Wait for the rate limiter without making a request.
|
|
489
|
+
|
|
490
|
+
Useful for non-`fetch` operations that still need to respect the
|
|
491
|
+
cross-process rate limit — for example, polling loops or pre-streaming
|
|
492
|
+
handshakes.
|
|
493
|
+
|
|
494
|
+
Args:
|
|
495
|
+
min_sleep: Minimum time to sleep in seconds before returning.
|
|
496
|
+
"""
|
|
497
|
+
self._limiter.wait(min_sleep=min_sleep)
|
|
498
|
+
|
|
499
|
+
def _compute_backoff(self, attempt: int, retry_after: float | None = None) -> float:
|
|
500
|
+
"""Compute the delay before the next retry.
|
|
501
|
+
|
|
502
|
+
Uses exponential backoff `base * 2^attempt` capped at `backoff_max`, with
|
|
503
|
+
optional uniform jitter. If the server provided a `Retry-After` value, the
|
|
504
|
+
returned delay is at least that large.
|
|
505
|
+
|
|
506
|
+
Args:
|
|
507
|
+
attempt: Zero-based retry attempt number (0 = first *retry*).
|
|
508
|
+
retry_after: Optional server `Retry-After` value in seconds.
|
|
509
|
+
|
|
510
|
+
Returns:
|
|
511
|
+
Delay in seconds.
|
|
512
|
+
"""
|
|
513
|
+
delay = self.backoff_base * (2**attempt)
|
|
514
|
+
if retry_after is not None:
|
|
515
|
+
delay = max(delay, retry_after)
|
|
516
|
+
delay = min(delay, self.backoff_max)
|
|
517
|
+
if self.jitter > 0:
|
|
518
|
+
delay += random.uniform(0, self.jitter)
|
|
519
|
+
return delay
|
|
520
|
+
|
|
521
|
+
def _resolve_url(self, url: str) -> str:
|
|
522
|
+
"""Resolve *url* against `base_url`."""
|
|
523
|
+
if "://" not in url:
|
|
524
|
+
return urllib.parse.urljoin(self.base_url, url)
|
|
525
|
+
if not url.startswith(self.base_url):
|
|
526
|
+
raise ValueError(f"URL {url!r} does not match base_url {self.base_url!r}")
|
|
527
|
+
return url
|
|
528
|
+
|
|
529
|
+
def _build_request(
|
|
530
|
+
self,
|
|
531
|
+
url: str,
|
|
532
|
+
method: str,
|
|
533
|
+
headers: dict[str, str] | None,
|
|
534
|
+
data: bytes | None,
|
|
535
|
+
json_body: Any | None,
|
|
536
|
+
) -> urllib.request.Request:
|
|
537
|
+
"""Build a `urllib.request.Request` from the given parameters."""
|
|
538
|
+
merged_headers = {
|
|
539
|
+
"User-Agent": self.user_agent,
|
|
540
|
+
"Accept-Encoding": "gzip",
|
|
541
|
+
}
|
|
542
|
+
if self._referer:
|
|
543
|
+
merged_headers["Referer"] = self._referer
|
|
544
|
+
# Must be last: Give priority to user-provided headers.
|
|
545
|
+
merged_headers.update(self.default_headers)
|
|
546
|
+
if headers:
|
|
547
|
+
merged_headers.update(headers)
|
|
548
|
+
|
|
549
|
+
body: bytes | None = data
|
|
550
|
+
if json_body is not None:
|
|
551
|
+
body = json.dumps(json_body).encode("utf-8")
|
|
552
|
+
merged_headers.setdefault("Content-Type", "application/json")
|
|
553
|
+
|
|
554
|
+
req = urllib.request.Request(
|
|
555
|
+
url,
|
|
556
|
+
data=body,
|
|
557
|
+
headers=merged_headers,
|
|
558
|
+
method=method,
|
|
559
|
+
)
|
|
560
|
+
return req
|
|
561
|
+
|
|
562
|
+
def fetch(
|
|
563
|
+
self,
|
|
564
|
+
url: str,
|
|
565
|
+
*,
|
|
566
|
+
method: str = "GET",
|
|
567
|
+
headers: dict[str, str] | None = None,
|
|
568
|
+
data: bytes | None = None,
|
|
569
|
+
json_body: Any | None = None,
|
|
570
|
+
timeout: float | None = None,
|
|
571
|
+
max_retries: int | None = None,
|
|
572
|
+
) -> HttpResponse:
|
|
573
|
+
"""Execute an HTTP request with rate limiting and retries.
|
|
574
|
+
|
|
575
|
+
On each attempt the client:
|
|
576
|
+
|
|
577
|
+
1. Waits for the rate limiter (cross-process file-lock).
|
|
578
|
+
2. Sends the request via `urllib.request`.
|
|
579
|
+
3. On success (2xx), returns an `HttpResponse`.
|
|
580
|
+
4. On a retryable HTTP error (429, 5xx) or a network error, sleeps for an
|
|
581
|
+
exponential backoff delay (with optional jitter and `Retry-After`
|
|
582
|
+
support) before retrying.
|
|
583
|
+
5. On a non-retryable HTTP error, raises `HttpError` immediately.
|
|
584
|
+
|
|
585
|
+
Args:
|
|
586
|
+
url: Request URL.
|
|
587
|
+
method: HTTP method (`GET`, `POST`, etc.).
|
|
588
|
+
headers: Extra HTTP headers (merged with the default User-Agent).
|
|
589
|
+
data: Raw request body bytes (mutually exclusive with *json_body*).
|
|
590
|
+
json_body: JSON-serializable request body. Automatically sets
|
|
591
|
+
`Content-Type: application/json`.
|
|
592
|
+
timeout: Per-request timeout in seconds (overrides the client-level
|
|
593
|
+
default).
|
|
594
|
+
max_retries: Override for the maximum number of retry attempts.
|
|
595
|
+
|
|
596
|
+
Returns:
|
|
597
|
+
`HttpResponse` containing the response data.
|
|
598
|
+
|
|
599
|
+
Raises:
|
|
600
|
+
HttpError: On non-retryable HTTP errors or after exhausting all
|
|
601
|
+
retry attempts.
|
|
602
|
+
ValueError: If both *data* and *json_body* are provided.
|
|
603
|
+
"""
|
|
604
|
+
with self._open_stream(
|
|
605
|
+
url, method, headers, data, json_body, timeout, max_retries
|
|
606
|
+
) as resp:
|
|
607
|
+
stream = _maybe_decompress(resp)
|
|
608
|
+
body = stream.read()
|
|
609
|
+
encoding = resp.headers.get_content_charset() or DEFAULT_CHARSET
|
|
610
|
+
return HttpResponse(
|
|
611
|
+
data=body,
|
|
612
|
+
status_code=resp.status,
|
|
613
|
+
headers=dict(resp.headers),
|
|
614
|
+
url=resp.url,
|
|
615
|
+
encoding=encoding,
|
|
616
|
+
)
|
|
617
|
+
|
|
618
|
+
def fetch_json(self, url: str, **kwargs) -> Any:
|
|
619
|
+
"""Fetch a URL and parse the response as JSON.
|
|
620
|
+
|
|
621
|
+
Convenience wrapper around `fetch()` that adds an
|
|
622
|
+
`Accept: application/json` header (if not already set) and returns the
|
|
623
|
+
parsed JSON body.
|
|
624
|
+
|
|
625
|
+
Args:
|
|
626
|
+
url: URL to fetch.
|
|
627
|
+
**kwargs: Keyword arguments to pass to `fetch()`.
|
|
628
|
+
|
|
629
|
+
Returns:
|
|
630
|
+
Parsed JSON (dict, list, str, etc.).
|
|
631
|
+
|
|
632
|
+
Raises:
|
|
633
|
+
HttpError: On HTTP or network errors.
|
|
634
|
+
json.JSONDecodeError: If the response body is not valid JSON.
|
|
635
|
+
"""
|
|
636
|
+
hdrs = kwargs.pop("headers", None) or {}
|
|
637
|
+
hdrs.setdefault("Accept", "application/json")
|
|
638
|
+
resp = self.fetch(url, headers=hdrs, **kwargs)
|
|
639
|
+
return resp.json()
|
|
640
|
+
|
|
641
|
+
def fetch_bytes(self, url: str, **kwargs) -> bytes:
|
|
642
|
+
"""Fetch a URL and return the raw response body.
|
|
643
|
+
|
|
644
|
+
Convenience wrapper for binary downloads (PDFs, images, archives, etc.).
|
|
645
|
+
|
|
646
|
+
Args:
|
|
647
|
+
url: URL to fetch.
|
|
648
|
+
**kwargs: Keyword arguments to pass to `fetch()`.
|
|
649
|
+
|
|
650
|
+
Returns:
|
|
651
|
+
Raw response bytes.
|
|
652
|
+
|
|
653
|
+
Raises:
|
|
654
|
+
HttpError: On HTTP or network errors.
|
|
655
|
+
"""
|
|
656
|
+
return self.fetch(url, **kwargs).data
|
|
657
|
+
|
|
658
|
+
def fetch_text(self, url: str, **kwargs) -> str:
|
|
659
|
+
"""Fetch a URL and return the response body as a decoded string.
|
|
660
|
+
|
|
661
|
+
Convenience wrapper for text-based APIs (XML, TSV, plain text).
|
|
662
|
+
|
|
663
|
+
Args:
|
|
664
|
+
url: URL to fetch.
|
|
665
|
+
**kwargs: Keyword arguments to pass to `fetch()`.
|
|
666
|
+
|
|
667
|
+
Returns:
|
|
668
|
+
Response body decoded using the charset from Content-Type.
|
|
669
|
+
|
|
670
|
+
Raises:
|
|
671
|
+
HttpError: On HTTP or network errors.
|
|
672
|
+
"""
|
|
673
|
+
return self.fetch(url, **kwargs).text
|
|
674
|
+
|
|
675
|
+
@contextlib.contextmanager
|
|
676
|
+
def _open_stream(
|
|
677
|
+
self,
|
|
678
|
+
url: str,
|
|
679
|
+
method: str,
|
|
680
|
+
headers: dict[str, str] | None,
|
|
681
|
+
data: bytes | None,
|
|
682
|
+
json_body: Any | None,
|
|
683
|
+
timeout: float | None,
|
|
684
|
+
max_retries: int | None = None,
|
|
685
|
+
) -> Iterator[http.client.HTTPResponse]:
|
|
686
|
+
"""Open an HTTP response with rate limiting and retries (internal).
|
|
687
|
+
|
|
688
|
+
Handles argument validation, rate limiting, request dispatch, and
|
|
689
|
+
error checking. Yields the raw `http.client.HTTPResponse` and
|
|
690
|
+
guarantees `response.close()` on exit.
|
|
691
|
+
|
|
692
|
+
The **connection phase** (before any data flows) is retried on
|
|
693
|
+
transient errors (429, 5xx) with the same backoff logic as
|
|
694
|
+
`fetch()`. Once a 2xx response is yielded, no further retries
|
|
695
|
+
are attempted — streaming data is not idempotently resumable.
|
|
696
|
+
|
|
697
|
+
On **2xx responses** that include an `X-Throttling-Control`
|
|
698
|
+
header, proactive backpressure is applied so the next request
|
|
699
|
+
is delayed before hitting a hard limit.
|
|
700
|
+
|
|
701
|
+
Args:
|
|
702
|
+
url: Request URL.
|
|
703
|
+
method: HTTP method.
|
|
704
|
+
headers: Extra HTTP headers.
|
|
705
|
+
data: Raw request body bytes.
|
|
706
|
+
json_body: JSON-serializable request body.
|
|
707
|
+
timeout: Per-request timeout override.
|
|
708
|
+
max_retries: Override for maximum connection retry attempts.
|
|
709
|
+
|
|
710
|
+
Yields:
|
|
711
|
+
An open `http.client.HTTPResponse` ready for streaming reads.
|
|
712
|
+
|
|
713
|
+
Raises:
|
|
714
|
+
HttpError: On HTTP errors (non-2xx status) or network errors.
|
|
715
|
+
ValueError: If both *data* and *json_body* are provided.
|
|
716
|
+
"""
|
|
717
|
+
if data is not None and json_body is not None:
|
|
718
|
+
raise ValueError("Cannot specify both 'data' and 'json_body'.")
|
|
719
|
+
|
|
720
|
+
url = self._resolve_url(url)
|
|
721
|
+
|
|
722
|
+
effective_timeout = timeout if timeout is not None else self.timeout
|
|
723
|
+
effective_retries = max_retries if max_retries is not None else self.max_retries
|
|
724
|
+
|
|
725
|
+
last_exc: Exception | None = None
|
|
726
|
+
next_min_sleep = 0.0
|
|
727
|
+
for attempt in range(effective_retries + 1):
|
|
728
|
+
current_min_sleep = max(next_min_sleep, self._next_min_sleep)
|
|
729
|
+
self._limiter.wait(min_sleep=current_min_sleep)
|
|
730
|
+
self._next_min_sleep = 0.0
|
|
731
|
+
req = self._build_request(url, method, headers, data, json_body)
|
|
732
|
+
|
|
733
|
+
try:
|
|
734
|
+
response = urllib.request.urlopen(req, timeout=effective_timeout)
|
|
735
|
+
except urllib.error.HTTPError as exc:
|
|
736
|
+
status = exc.code
|
|
737
|
+
error_body = exc.read()
|
|
738
|
+
retry_after = _parse_retry_after(exc.headers)
|
|
739
|
+
exc.close()
|
|
740
|
+
|
|
741
|
+
if (
|
|
742
|
+
status in self.retryable_status_codes
|
|
743
|
+
and attempt < effective_retries
|
|
744
|
+
):
|
|
745
|
+
next_min_sleep = self._compute_backoff(attempt, retry_after)
|
|
746
|
+
logging.info(
|
|
747
|
+
"HttpClient[%s]: HTTP %d from %s — retrying in ≥%.1fs"
|
|
748
|
+
" (attempt %d/%d)",
|
|
749
|
+
self.hostname,
|
|
750
|
+
status,
|
|
751
|
+
url,
|
|
752
|
+
next_min_sleep,
|
|
753
|
+
attempt + 1,
|
|
754
|
+
effective_retries + 1,
|
|
755
|
+
)
|
|
756
|
+
last_exc = HttpError(
|
|
757
|
+
f"HTTP Error {status} while fetching {url}",
|
|
758
|
+
status_code=status,
|
|
759
|
+
body=error_body,
|
|
760
|
+
url=url,
|
|
761
|
+
)
|
|
762
|
+
continue
|
|
763
|
+
|
|
764
|
+
hint = ""
|
|
765
|
+
if status == 403:
|
|
766
|
+
hint = (
|
|
767
|
+
f" (Hint: this may be caused by the User-Agent"
|
|
768
|
+
f" '{self.user_agent}'. Override it by setting the environment"
|
|
769
|
+
f" variable {USER_AGENT_ENV_VAR}, e.g.:"
|
|
770
|
+
f' {USER_AGENT_ENV_VAR}="<enter_your_custom_user_agent>"'
|
|
771
|
+
f" python3 script.py ...)"
|
|
772
|
+
)
|
|
773
|
+
raise HttpError(
|
|
774
|
+
f"HTTP Error {status} while fetching {url}{hint}",
|
|
775
|
+
status_code=status,
|
|
776
|
+
body=error_body,
|
|
777
|
+
url=url,
|
|
778
|
+
) from exc
|
|
779
|
+
except (urllib.error.URLError, OSError) as exc:
|
|
780
|
+
if attempt < effective_retries:
|
|
781
|
+
next_min_sleep = self._compute_backoff(attempt)
|
|
782
|
+
logging.info(
|
|
783
|
+
"HttpClient[%s]: Network error (%s) — retrying in ≥%.1fs"
|
|
784
|
+
" (attempt %d/%d)",
|
|
785
|
+
self.hostname,
|
|
786
|
+
exc,
|
|
787
|
+
next_min_sleep,
|
|
788
|
+
attempt + 1,
|
|
789
|
+
effective_retries + 1,
|
|
790
|
+
)
|
|
791
|
+
last_exc = exc
|
|
792
|
+
continue
|
|
793
|
+
raise HttpError(
|
|
794
|
+
f"Network error fetching {url}: {exc}", url=url
|
|
795
|
+
) from exc
|
|
796
|
+
|
|
797
|
+
# 2xx success.
|
|
798
|
+
throttle_delay = _parse_throttle_control(response.headers)
|
|
799
|
+
if throttle_delay > 0:
|
|
800
|
+
logging.info(
|
|
801
|
+
"HttpClient[%s]: X-Throttling-Control backpressure %.1fs from %s",
|
|
802
|
+
self.hostname,
|
|
803
|
+
throttle_delay,
|
|
804
|
+
url,
|
|
805
|
+
)
|
|
806
|
+
self._next_min_sleep = throttle_delay
|
|
807
|
+
|
|
808
|
+
try:
|
|
809
|
+
yield response
|
|
810
|
+
finally:
|
|
811
|
+
response.close()
|
|
812
|
+
return
|
|
813
|
+
|
|
814
|
+
# Should not be reachable.
|
|
815
|
+
raise HttpError(
|
|
816
|
+
f"Max retries ({effective_retries}) exceeded for {url}",
|
|
817
|
+
url=url,
|
|
818
|
+
) from last_exc
|
|
819
|
+
|
|
820
|
+
def stream_lines(
|
|
821
|
+
self,
|
|
822
|
+
url: str,
|
|
823
|
+
*,
|
|
824
|
+
method: str = "GET",
|
|
825
|
+
headers: dict[str, str] | None = None,
|
|
826
|
+
data: bytes | None = None,
|
|
827
|
+
json_body: Any | None = None,
|
|
828
|
+
timeout: float | None = None,
|
|
829
|
+
max_retries: int | None = None,
|
|
830
|
+
) -> Iterator[str]:
|
|
831
|
+
"""Stream an HTTP response line-by-line without buffering.
|
|
832
|
+
|
|
833
|
+
Useful for large result sets (e.g. UniProt `/stream` which can
|
|
834
|
+
return up to 10M lines). The response is streamed via
|
|
835
|
+
`urllib.request` with automatic gzip decompression.
|
|
836
|
+
|
|
837
|
+
Rate-limits before each attempt. The **connection phase** is
|
|
838
|
+
retried on transient errors (429, 5xx), but once data starts
|
|
839
|
+
streaming, no further retries are attempted.
|
|
840
|
+
|
|
841
|
+
Args:
|
|
842
|
+
url: Request URL.
|
|
843
|
+
method: HTTP method.
|
|
844
|
+
headers: Extra HTTP headers.
|
|
845
|
+
data: Raw request body bytes (mutually exclusive with *json_body*).
|
|
846
|
+
json_body: JSON-serializable request body.
|
|
847
|
+
timeout: Per-request timeout in seconds (overrides the client default).
|
|
848
|
+
This is the timeout for the initial connection, not for reading
|
|
849
|
+
individual lines.
|
|
850
|
+
max_retries: Override for maximum connection retry attempts.
|
|
851
|
+
|
|
852
|
+
Yields:
|
|
853
|
+
Each line of the response body, decoded as text (trailing newline
|
|
854
|
+
stripped).
|
|
855
|
+
|
|
856
|
+
Raises:
|
|
857
|
+
HttpError: On HTTP errors (non-2xx status).
|
|
858
|
+
"""
|
|
859
|
+
with self._open_stream(
|
|
860
|
+
url, method, headers, data, json_body, timeout, max_retries
|
|
861
|
+
) as response:
|
|
862
|
+
stream = _maybe_decompress(response)
|
|
863
|
+
encoding = response.headers.get_content_charset() or DEFAULT_CHARSET
|
|
864
|
+
for raw_line in stream:
|
|
865
|
+
line = raw_line.decode(encoding).rstrip("\r\n")
|
|
866
|
+
yield line
|
|
867
|
+
|
|
868
|
+
def stream_bytes(
|
|
869
|
+
self,
|
|
870
|
+
url: str,
|
|
871
|
+
*,
|
|
872
|
+
method: str = "GET",
|
|
873
|
+
headers: dict[str, str] | None = None,
|
|
874
|
+
data: bytes | None = None,
|
|
875
|
+
json_body: Any | None = None,
|
|
876
|
+
timeout: float | None = None,
|
|
877
|
+
chunk_size: int = 8192,
|
|
878
|
+
max_retries: int | None = None,
|
|
879
|
+
) -> Iterator[bytes]:
|
|
880
|
+
"""Stream an HTTP response as raw byte chunks without buffering.
|
|
881
|
+
|
|
882
|
+
Symmetric with `stream_lines` but for binary content (PDFs, archives,
|
|
883
|
+
images, etc.). Each iteration yields a chunk of up to *chunk_size* bytes.
|
|
884
|
+
Chunks are **transfer-decoded**: if the server applied
|
|
885
|
+
`Content-Encoding: gzip` in transit, the yielded bytes are the
|
|
886
|
+
decompressed content.
|
|
887
|
+
|
|
888
|
+
Rate-limits before each attempt. The **connection phase** is retried on
|
|
889
|
+
transient errors (429, 5xx), but once data starts streaming, no further
|
|
890
|
+
retries are attempted.
|
|
891
|
+
|
|
892
|
+
Example:
|
|
893
|
+
|
|
894
|
+
with open("paper.pdf", "wb") as f:
|
|
895
|
+
for chunk in client.stream_bytes(url):
|
|
896
|
+
f.write(chunk)
|
|
897
|
+
|
|
898
|
+
Args:
|
|
899
|
+
url: Request URL.
|
|
900
|
+
method: HTTP method.
|
|
901
|
+
headers: Extra HTTP headers.
|
|
902
|
+
data: Raw request body bytes (mutually exclusive with *json_body*).
|
|
903
|
+
json_body: JSON-serializable request body.
|
|
904
|
+
timeout: Per-request timeout in seconds (overrides the client default).
|
|
905
|
+
This is the timeout for the initial connection, not for reading
|
|
906
|
+
individual chunks.
|
|
907
|
+
chunk_size: Maximum number of bytes per yielded chunk.
|
|
908
|
+
max_retries: Override for maximum connection retry attempts.
|
|
909
|
+
|
|
910
|
+
Yields:
|
|
911
|
+
Non-empty `bytes` chunks of the response body.
|
|
912
|
+
|
|
913
|
+
Raises:
|
|
914
|
+
HttpError: On HTTP errors (non-2xx status).
|
|
915
|
+
"""
|
|
916
|
+
with self._open_stream(
|
|
917
|
+
url, method, headers, data, json_body, timeout, max_retries
|
|
918
|
+
) as response:
|
|
919
|
+
stream = _maybe_decompress(response)
|
|
920
|
+
while True:
|
|
921
|
+
chunk = stream.read(chunk_size)
|
|
922
|
+
if not chunk:
|
|
923
|
+
break
|
|
924
|
+
yield chunk
|
polite_http/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: polite-http
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A courteous, dependency-free HTTP client with rate limiting, retries, and backoff.
|
|
5
|
+
Project-URL: Homepage, https://github.com/doug/polite-http
|
|
6
|
+
Project-URL: Repository, https://github.com/doug/polite-http
|
|
7
|
+
Project-URL: Issues, https://github.com/doug/polite-http/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/doug/polite-http/blob/main/CHANGELOG.md
|
|
9
|
+
Author-email: Doug Fritz <dougfritz@gmail.com>
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
License-File: NOTICE
|
|
13
|
+
Keywords: backoff,client,http,rate-limiting,retry,throttling,urllib
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
25
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
26
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
27
|
+
Classifier: Typing :: Typed
|
|
28
|
+
Requires-Python: >=3.9
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: mypy>=1.8; extra == 'dev'
|
|
31
|
+
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
|
|
32
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
33
|
+
Requires-Dist: ruff>=0.4; extra == 'dev'
|
|
34
|
+
Description-Content-Type: text/markdown
|
|
35
|
+
|
|
36
|
+
# polite-http
|
|
37
|
+
|
|
38
|
+
[](https://github.com/doug/polite-http/actions/workflows/ci.yml)
|
|
39
|
+
[](https://pypi.org/project/polite-http/)
|
|
40
|
+
[](https://pypi.org/project/polite-http/)
|
|
41
|
+
[](LICENSE)
|
|
42
|
+
|
|
43
|
+
A courteous, **dependency-free** HTTP client for Python. It plays nice with
|
|
44
|
+
rate-limited APIs out of the box:
|
|
45
|
+
|
|
46
|
+
- **Per-host rate limiting** — cross-process, via a shared file lock.
|
|
47
|
+
- **Automatic retries** on transient errors (HTTP 429, 5xx) and network errors.
|
|
48
|
+
- **Exponential backoff** with optional jitter.
|
|
49
|
+
- **`Retry-After`** support (server-directed backoff, both seconds and
|
|
50
|
+
HTTP-date forms).
|
|
51
|
+
- **`X-Throttling-Control`** proactive backpressure (as used by PubChem / NCBI).
|
|
52
|
+
- **Streaming** helpers for large line-oriented and binary responses.
|
|
53
|
+
- **Zero third-party dependencies** — built entirely on the standard library
|
|
54
|
+
(`urllib.request`).
|
|
55
|
+
|
|
56
|
+
## Installation
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pip install polite-http
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Requires Python 3.9+. Cross-process rate limiting works on Linux, macOS, and
|
|
63
|
+
Windows — it uses `fcntl` on POSIX and `msvcrt` on Windows for the shared file
|
|
64
|
+
lock (both standard library). On the rare platform that provides neither, it
|
|
65
|
+
falls back to a best-effort in-process timer.
|
|
66
|
+
|
|
67
|
+
## Quick start
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from polite_http import HttpClient
|
|
71
|
+
|
|
72
|
+
# Scope a client to a base URL and a steady-state rate of 3 requests/second.
|
|
73
|
+
client = HttpClient("https://eutils.ncbi.nlm.nih.gov/entrez/eutils/", qps=3)
|
|
74
|
+
|
|
75
|
+
# GET + parse JSON (relative paths are resolved against the base URL).
|
|
76
|
+
data = client.fetch_json("esummary.fcgi?db=pubmed&id=123456")
|
|
77
|
+
|
|
78
|
+
# POST a JSON body.
|
|
79
|
+
result = client.fetch_json(
|
|
80
|
+
"esearch.fcgi",
|
|
81
|
+
method="POST",
|
|
82
|
+
json_body={"db": "pubmed", "term": "cancer"},
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
# Download raw bytes with a custom timeout.
|
|
86
|
+
pdf = client.fetch_bytes(
|
|
87
|
+
"efetch.fcgi?db=pubmed&id=123456&rettype=abstract",
|
|
88
|
+
timeout=60,
|
|
89
|
+
)
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Streaming
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
# Stream a large response line-by-line without buffering it all in memory.
|
|
96
|
+
for line in client.stream_lines("large-export.tsv"):
|
|
97
|
+
process(line)
|
|
98
|
+
|
|
99
|
+
# Stream binary content in chunks (e.g. to a file).
|
|
100
|
+
with open("paper.pdf", "wb") as f:
|
|
101
|
+
for chunk in client.stream_bytes("paper.pdf"):
|
|
102
|
+
f.write(chunk)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Configuration
|
|
106
|
+
|
|
107
|
+
`HttpClient` accepts the following keyword arguments:
|
|
108
|
+
|
|
109
|
+
| Argument | Default | Description |
|
|
110
|
+
| --- | --- | --- |
|
|
111
|
+
| `qps` | _required_ | Maximum queries per second (steady state). |
|
|
112
|
+
| `default_headers` | `None` | Headers added to every request. |
|
|
113
|
+
| `max_retries` | `7` | Retry attempts for transient errors (total attempts = `max_retries + 1`). |
|
|
114
|
+
| `timeout` | `60.0` | Per-request timeout in seconds. |
|
|
115
|
+
| `backoff_base` | `3.0` | Base delay for exponential backoff. |
|
|
116
|
+
| `backoff_max` | `180.0` | Cap on backoff delay. |
|
|
117
|
+
| `jitter` | `0.5` | Max uniform random jitter added to each backoff. |
|
|
118
|
+
| `user_agent` | env / `""` | `User-Agent` header; falls back to `POLITE_HTTP_USER_AGENT`. |
|
|
119
|
+
| `retryable_status_codes` | `{429, 500, 502, 503, 504}` | Status codes that trigger a retry. |
|
|
120
|
+
| `referer` | `None` | Optional `Referer` header sent with every request. |
|
|
121
|
+
|
|
122
|
+
### Environment variables
|
|
123
|
+
|
|
124
|
+
- `POLITE_HTTP_USER_AGENT` — default `User-Agent` when one isn't passed
|
|
125
|
+
explicitly. Many APIs (e.g. NCBI) reject requests without a descriptive
|
|
126
|
+
User-Agent, so setting this is recommended.
|
|
127
|
+
- `POLITE_HTTP_LOCK_DIR` — directory for the cross-process rate-limit lock
|
|
128
|
+
files (defaults to the system temp directory).
|
|
129
|
+
|
|
130
|
+
## Error handling
|
|
131
|
+
|
|
132
|
+
Failed requests raise `HttpError`, which carries the `status_code`, raw `body`
|
|
133
|
+
bytes, and `url`:
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
from polite_http import HttpClient, HttpError
|
|
137
|
+
|
|
138
|
+
client = HttpClient("https://api.example.com/", qps=5)
|
|
139
|
+
try:
|
|
140
|
+
data = client.fetch_json("widgets/42")
|
|
141
|
+
except HttpError as exc:
|
|
142
|
+
print(exc.status_code, exc.url)
|
|
143
|
+
if exc.body:
|
|
144
|
+
print(exc.json()) # parse the error body as JSON, if applicable
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## Acknowledgements
|
|
148
|
+
|
|
149
|
+
The HTTP client at the heart of this package is derived from the
|
|
150
|
+
[`science-skills`](https://github.com/google-deepmind/science-skills) project by
|
|
151
|
+
Google DeepMind, used under the Apache License 2.0. See [`NOTICE`](NOTICE) for
|
|
152
|
+
details of the changes.
|
|
153
|
+
|
|
154
|
+
## License
|
|
155
|
+
|
|
156
|
+
[Apache License 2.0](LICENSE).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
polite_http/__init__.py,sha256=LtTyWZmJ90euuXweYPcRHZxGKQ_JdoTG4kECuelGmas,1440
|
|
2
|
+
polite_http/http_client.py,sha256=2fuYy-zh4XWSufHNHHyhF6EeGEl3n4CRFDRELat41xI,32369
|
|
3
|
+
polite_http/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
polite_http-0.1.0.dist-info/METADATA,sha256=-VqUDgXS8Ud2Y6cWgnQoSKMTjYwvyt-EG2iBUWmhp70,5955
|
|
5
|
+
polite_http-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
6
|
+
polite_http-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
7
|
+
polite_http-0.1.0.dist-info/licenses/NOTICE,sha256=DIzzTLYPkNV3zIAqWqrHkxQ_TCGTyKI41Vq9oUi7lh0,1312
|
|
8
|
+
polite_http-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
polite-http
|
|
2
|
+
Copyright 2026 polite-http contributors
|
|
3
|
+
|
|
4
|
+
This product includes software developed by Google LLC as part of the
|
|
5
|
+
science-skills project (https://github.com/google-deepmind/science-skills),
|
|
6
|
+
licensed under the Apache License, Version 2.0.
|
|
7
|
+
|
|
8
|
+
The file `src/polite_http/http_client.py` is derived from
|
|
9
|
+
`skills/scienceskillscommon/http_client.py` in that project.
|
|
10
|
+
|
|
11
|
+
Modifications made by the polite-http contributors include:
|
|
12
|
+
|
|
13
|
+
* Repackaged as the standalone, installable `polite_http` Python package.
|
|
14
|
+
* Renamed the project/lock-file prefix from "science-skills" to
|
|
15
|
+
"polite-http".
|
|
16
|
+
* Renamed the User-Agent environment variable from
|
|
17
|
+
"SCIENCE_SKILLS_USER_AGENT" to "POLITE_HTTP_USER_AGENT" (exposed as
|
|
18
|
+
`polite_http.USER_AGENT_ENV_VAR`).
|
|
19
|
+
* Replaced the science-skills-specific `referer_skill` parameter and Referer
|
|
20
|
+
template with a generic `referer` string parameter.
|
|
21
|
+
* Added cross-platform cross-process locking: `fcntl` on POSIX and `msvcrt`
|
|
22
|
+
on Windows, with a best-effort in-process timer fallback on the rare
|
|
23
|
+
platform that provides neither (still standard-library only).
|
|
24
|
+
* Made the rate-limit lock directory configurable via the
|
|
25
|
+
"POLITE_HTTP_LOCK_DIR" environment variable (defaulting to the system temp
|
|
26
|
+
directory).
|
|
27
|
+
* Added input validation for non-positive `qps`.
|