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 — a single float, or a
|
|
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 libs/core/src/earthlens/base/http.py
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 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 | |
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
|
Timeout
|
Per-request timeout in seconds — a single float bounds
both the connect and read phases, or pass a |
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 libs/core/src/earthlens/base/http.py
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 | |
download(url, dest, *, chunk=DEFAULT_CHUNK_SIZE, progress=True, atomic=True, expect_magic=None, 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
|
expect_magic
|
bytes | tuple[bytes, ...] | None
|
One or more byte prefixes the body must start with
(e.g. |
None
|
headers
|
dict[str, str] | None
|
Per-request headers merged over the client defaults. |
None
|
timeout
|
Timeout | None
|
Per-request timeout override (seconds), as a single
float or a |
None
|
**kwargs
|
Any
|
Extra keyword arguments forwarded to |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
HTTPError
|
On an error status — |
Source code in libs/core/src/earthlens/base/http.py
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 | |
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 libs/core/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
|
Timeout | None
|
Per-request timeout override (seconds), as a single
float or a |
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 libs/core/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. |