HTTP client (earthlens.base.http)#
HttpClient is the shared requests-based transport for the REST-style backends. It owns the chores every
backend used to hand-roll — a pooled session, a sensible User-Agent, a per-request timeout, a
Retry-After-aware 429/5xx back-off loop, JSON decoding, and a streamed download with a progress bar — so a
new backend keeps only the API-shaped parts: endpoint paths, query params, pagination, auth-header values, and
response parsing.
Don't hand-roll a session or a retry loop. If you find yourself writing
requests.Session(), awhileloop that inspects429/Retry-After, or aniter_contentchunk loop, reach forHttpClientinstead. Backends that pre-date it are being migrated onto it.
Consuming it#
Construct one client per backend with the default headers it needs, then call the verbs:
from earthlens.base.http import HttpClient
http = HttpClient(headers={"X-API-Key": api_key}, timeout=60.0)
# JSON GET with automatic 429/5xx retry + Retry-After honouring:
payload = http.get_json("https://api.example.org/v1/things", params={"bbox": "1,2,3,4"})
# Streamed download to disk with a tqdm bar (sized from Content-Length):
http.download("https://example.org/big.tif", dest, progress=True)
The default User-Agent is earthlens/{version} — deliberately non-Mozilla, because the DIGITAL.CSIC
Anubis anti-bot wall (SPEIbase) blocks browser-like agents. Pass user_agent= for a descriptive contact string
(e.g. Overpass / ohsome etiquette).
Testability#
Both the transport and the wait are injectable, so the whole client is unit-testable with a fake session and no real delays:
Pagination and response-envelope parsing stay in each backend — the client owns only how bytes move, never
the API shape.
API#
earthlens.base.http.HttpClient
#
Reusable HTTP transport: session, headers, timeout, retry, download.
Wraps a :class:requests.Session, attaching default headers (a
non-Mozilla User-Agent and Accept-Encoding: gzip, deflate) to
every request and applying a shared timeout. The verbs
(:meth:get, :meth:post, :meth:request) route through a
Retry-After-aware back-off loop; :meth:get_json decodes the JSON
body and :meth:download streams a response to disk. Both the
session and the sleep function are injectable so the client is fully
unit-testable without a live network.
Default headers set at construction are merged with (and overridden
by) any per-request headers=, so a backend expresses its quirks —
openaq's X-API-Key, a descriptive osm contact User-Agent — without
subclassing.
Attributes:
| Name | Type | Description |
|---|---|---|
timeout |
Per-request timeout in seconds. |
|
max_retries |
Maximum retries on a retryable status before raising. |
|
backoff_factor |
Base seconds for exponential back-off when no
|
|
status_forcelist |
HTTP statuses that trigger a retry. |
|
max_backoff |
Ceiling in seconds on any single retry wait. |
|
retry_on_exceptions |
Transport exception types that trigger a retry. |
|
raise_for_status |
Whether the final response is |
|
min_interval |
Minimum seconds between consecutive requests. |
Examples:
- The default agent is non-Mozilla and version-stamped:
Source code in src/earthlens/base/http.py
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 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 | |
default_headers
property
#
Return a copy of the headers merged onto every request.
session
property
#
Return the underlying :class:requests.Session.
__init__(*, session=None, user_agent=None, headers=None, timeout=DEFAULT_TIMEOUT, max_retries=DEFAULT_MAX_RETRIES, backoff_factor=DEFAULT_BACKOFF_FACTOR, status_forcelist=DEFAULT_STATUS_FORCELIST, max_backoff=DEFAULT_MAX_BACKOFF, retry_on_exceptions=(), retry_predicate=None, raise_for_status=True, min_interval=0.0, clock=time.monotonic, sleep=time.sleep)
#
Build a client with default headers, timeout, and retry policy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
Session | None
|
An existing :class: |
None
|
user_agent
|
str | None
|
The default |
None
|
headers
|
dict[str, str] | None
|
Extra default headers merged onto every request
(e.g. |
None
|
timeout
|
float
|
Per-request timeout in seconds. |
DEFAULT_TIMEOUT
|
max_retries
|
int
|
Maximum retries on a retryable status before the last response's error is raised. |
DEFAULT_MAX_RETRIES
|
backoff_factor
|
float
|
Base seconds for exponential back-off when a
response carries no |
DEFAULT_BACKOFF_FACTOR
|
status_forcelist
|
tuple[int, ...]
|
HTTP statuses that trigger a retry. |
DEFAULT_STATUS_FORCELIST
|
max_backoff
|
float | None
|
Ceiling in seconds on any single retry wait, so a
large |
DEFAULT_MAX_BACKOFF
|
retry_on_exceptions
|
tuple[type[BaseException], ...]
|
Exception types that also trigger a retry
when raised by the transport (e.g.
|
()
|
retry_predicate
|
Callable[[Response], bool] | None
|
An optional callback |
None
|
raise_for_status
|
bool
|
Whether to call |
True
|
min_interval
|
float
|
Minimum seconds between consecutive requests
(a proactive client-side rate limit). |
0.0
|
clock
|
Callable[[], float]
|
Monotonic clock used for the |
monotonic
|
sleep
|
Callable[[float], None]
|
The sleep function used between retries and for the
throttle. Defaults to :func: |
sleep
|
Source code in src/earthlens/base/http.py
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 | |
download(url, dest, *, chunk=DEFAULT_CHUNK_SIZE, progress=True, atomic=True, headers=None, timeout=None, **kwargs)
#
Stream url to dest atomically, optionally showing a tqdm bar.
Absorbs the chunk-loop the streamed-download backends each
re-implement: streams with stream=True, sizes a progress bar
from Content-Length when present, and writes 1 MiB blocks. When
atomic (the default) it writes to a sibling <dest>.part and
renames on success, and it removes the temp on any failure — so a
crashed or interrupted download never leaves a truncated dest.
The whole download is retry-wrapped: a status in status_forcelist
or an exception in retry_on_exceptions retries the attempt (after
cleaning the temp), honouring the Retry-After/back-off policy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Absolute request URL. |
required |
dest
|
str | Path
|
Output file path. Parent directories are created. |
required |
chunk
|
int
|
Streaming block size in bytes (default 1 MiB). |
DEFAULT_CHUNK_SIZE
|
progress
|
bool
|
Show a |
True
|
atomic
|
bool
|
Write to |
True
|
headers
|
dict[str, str] | None
|
Per-request headers merged over the client defaults. |
None
|
timeout
|
float | None
|
Per-request timeout override (seconds). |
None
|
**kwargs
|
Any
|
Extra keyword arguments forwarded to |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
The |
Raises:
| Type | Description |
|---|---|
HTTPError
|
On an error status — |
Source code in src/earthlens/base/http.py
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 | |
get_json(url, **kwargs)
#
Send a GET request and decode the JSON response body.
Convenience over :meth:get for the REST endpoints that return
JSON envelopes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Absolute request URL. |
required |
**kwargs
|
Any
|
Keyword arguments forwarded to :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
The parsed JSON body (typically a |
Raises:
| Type | Description |
|---|---|
HTTPError
|
On a non-retryable error status, or after the retryable status is exhausted. |
Source code in src/earthlens/base/http.py
request(method, url, *, headers=None, timeout=None, raise_for_status=None, **kwargs)
#
Send one request with the default headers, timeout, and retry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
HTTP verb ( |
required |
url
|
str
|
Absolute request URL. |
required |
headers
|
dict[str, str] | None
|
Per-request headers merged over the client defaults. |
None
|
timeout
|
float | None
|
Per-request timeout override (seconds). Defaults to
the client's |
None
|
raise_for_status
|
bool | None
|
Per-request override of the client's
|
None
|
**kwargs
|
Any
|
Extra keyword arguments forwarded to |
{}
|
Returns:
| Type | Description |
|---|---|
Response
|
requests.Response: The response (after |
Raises:
| Type | Description |
|---|---|
HTTPError
|
On a non-retryable error status, or after
the retryable status is exhausted (when |
Source code in src/earthlens/base/http.py
stream(url, **kwargs)
#
Send a streaming GET (stream=True), retry-wrapped.
Returns the open response without consuming its body, so the
caller can iterate iter_content. Retries follow the same
Retry-After/back-off policy as the other verbs; the retry
decision reads only the status line, never the body.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Absolute request URL. |
required |
**kwargs
|
Any
|
Keyword arguments forwarded to :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
Response
|
requests.Response: The open streaming response. |