Drop urllib3 in favor of public gist (#1182)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Drop urllib3 in favor of public gist * Drop urllib3 coverage omit * Drop recommendation to use urllib3 transport during Requests migration * Add urllib3-transport to 3p pkgs * Drop urllib3 from dependencies list in README / docs home page
authored by Florimond Manca · committed by GitHub · parent 642aabd · Browse files · 8 files·+25 added−160 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Tom Christie <tom@tomchristie.com>
Diff stats
8 files+25 added−160 removed
- other:+25 added−160 removed
Provenance
- Commit
8fa8765- Tree
05b859b- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
642aabd
8 files changed+25 added−160 removed
modified:docs/advanced.md+8 added-5 removed
807 unmodified lines808 HTTPX's `Client` also accepts a `transport` argument. This argument allows you809 to provide a custom Transport object that will be used to perform the actual810 sending of the requests.811 812+### Usage813+814 For some advanced configuration you might need to instantiate a transport815 class directly, and pass it to the client instance. The `httpcore` package816 provides a `local_address` configuration that is only available via this817 low-level API.33 unmodified lines851 do not include any default values for configuring aspects such as the852 connection pooling details, so you'll need to provide more explicit853 configuration when using this API.854 853-HTTPX also currently ships with a transport that uses the excellent854-[`urllib3` library](https://urllib3.readthedocs.io/en/latest/), which can be855-used with the sync `Client`...855+### urllib3 transport856 857+This [public gist](https://gist.github.com/florimondmanca/d56764d78d748eb9f73165da388e546e) provides a transport that uses the excellent [`urllib3` library](https://urllib3.readthedocs.io/en/latest/), and can be used with the sync `Client`...858+859 ```pycon860 >>> import httpx861+>>> from urllib3_transport import URLLib3Transport859->>> client = httpx.Client(transport=httpx.URLLib3Transport())862+>>> client = httpx.Client(transport=URLLib3Transport())863 >>> client.get("https://example.org")864 <Response [200 OK]>865 ```866 864-Note that you'll need to install the `urllib3` package to use `URLLib3Transport`.867+### Writing custom transports868 869 A transport instance must implement the Transport API defined by870 [`httpcore`](https://www.encode.io/httpcore/api/). You871 should either subclass `httpcore.AsyncHTTPTransport` to implement a transport to32 unmodified linesmodified:docs/compatibility.md+6 added
81 unmodified lines8283848586878889909181 unmodified lines
## Mocking
If you need to mock HTTPX the same way that test utilities like `responses` and `requests-mock` does for `requests`, see [RESPX](https://github.com/lundberg/respx).
## Networking layer
`requests` defers most of its HTTP networking code to the excellent [`urllib3` library](https://urllib3.readthedocs.io/en/latest/).
On the other hand, HTTPX uses [HTTPCore](https://github.com/encode/httpcore) as its core HTTP networking layer, which is a different project than `urllib3`.modified:docs/index.md-1 removed
112 unmodified lines113 * `chardet` - Fallback auto-detection for response encoding.114 * `rfc3986` - URL parsing & normalization.115 * `idna` - Internationalized domain name support.116 * `sniffio` - Async library autodetection.117-* `urllib3` - Support for the `httpx.URLLib3Transport` class. *(Optional)*117 * `brotlipy` - Decoding for "brotli" compressed responses. *(Optional)*118 119 A huge amount of credit is due to `requests` for the API layout that120 much of this work follows, as well as to `urllib3` for plenty of design25 unmodified linesmodified:docs/third-party-packages.md+10 added
21 unmodified lines222324252627282930313233343521 unmodified lines
[GitHub](https://github.com/lundberg/respx) - [Documentation](https://lundberg.github.io/respx/)
A utility for mocking out the Python HTTPX library.
## Gists
<!-- NOTE: this list is in alphabetical order. -->
### urllib3-transport
[GitHub](https://gist.github.com/florimondmanca/d56764d78d748eb9f73165da388e546e)
This public gist provides an example implementation for a [custom transport](/advanced#custom-transports) implementation on top of the battle-tested [`urllib3`](https://urllib3.readthedocs.io) library.deleted:httpx/_transports/urllib3.py-149 removed
1-import socket2-from typing import Iterator, List, Mapping, Optional, Tuple3-4-import httpcore5-6-from .._config import create_ssl_context7-from .._content_streams import ByteStream, IteratorStream8-from .._exceptions import NetworkError, map_exceptions9-from .._types import CertTypes, VerifyTypes10-11-try:12- import urllib313- from urllib3.exceptions import MaxRetryError, SSLError14-except ImportError: # pragma: nocover15- urllib3 = None16-17-18-class URLLib3Transport(httpcore.SyncHTTPTransport):19- def __init__(20- self,21- *,22- verify: VerifyTypes = True,23- cert: CertTypes = None,24- trust_env: bool = None,25- pool_connections: int = 10,26- pool_maxsize: int = 10,27- pool_block: bool = False,28- ):29- assert (30- urllib3 is not None31- ), "urllib3 must be installed in order to use URLLib3Transport"32-33- self.pool = urllib3.PoolManager(34- ssl_context=create_ssl_context(35- verify=verify, cert=cert, trust_env=trust_env, http2=False36- ),37- num_pools=pool_connections,38- maxsize=pool_maxsize,39- block=pool_block,40- )41-42- def request(43- self,44- method: bytes,45- url: Tuple[bytes, bytes, Optional[int], bytes],46- headers: List[Tuple[bytes, bytes]] = None,47- stream: httpcore.SyncByteStream = None,48- timeout: Mapping[str, Optional[float]] = None,49- ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.SyncByteStream]:50- headers = [] if headers is None else headers51- stream = ByteStream(b"") if stream is None else stream52- timeout = {} if timeout is None else timeout53-54- urllib3_timeout = urllib3.util.Timeout(55- connect=timeout.get("connect"), read=timeout.get("read")56- )57-58- chunked = False59- content_length = 060- for header_key, header_value in headers:61- header_key = header_key.lower()62- if header_key == b"transfer-encoding":63- chunked = header_value == b"chunked"64- if header_key == b"content-length":65- content_length = int(header_value.decode("ascii"))66- body = stream if chunked or content_length else None67-68- scheme, host, port, path = url69- default_port = {b"http": 80, "https": 443}.get(scheme)70- if port is None or port == default_port:71- url_str = "%s://%s%s" % (72- scheme.decode("ascii"),73- host.decode("ascii"),74- path.decode("ascii"),75- )76- else:77- url_str = "%s://%s:%d%s" % (78- scheme.decode("ascii"),79- host.decode("ascii"),80- port,81- path.decode("ascii"),82- )83-84- with map_exceptions(85- {86- MaxRetryError: NetworkError,87- SSLError: NetworkError,88- socket.error: NetworkError,89- }90- ):91- conn = self.pool.urlopen(92- method=method.decode(),93- url=url_str,94- headers={95- key.decode("ascii"): value.decode("ascii") for key, value in headers96- },97- body=body,98- redirect=False,99- assert_same_host=False,100- retries=0,101- preload_content=False,102- chunked=chunked,103- timeout=urllib3_timeout,104- pool_timeout=timeout.get("pool"),105- )106-107- def response_bytes() -> Iterator[bytes]:108- with map_exceptions({socket.error: NetworkError}):109- for chunk in conn.stream(4096, decode_content=False):110- yield chunk111-112- status_code = conn.status113- headers = list(conn.headers.items())114- response_stream = IteratorStream(115- iterator=response_bytes(), close_func=conn.release_conn116- )117- return (b"HTTP/1.1", status_code, conn.reason, headers, response_stream)118-119- def close(self) -> None:120- self.pool.clear()121-122-123-class URLLib3ProxyTransport(URLLib3Transport):124- def __init__(125- self,126- *,127- proxy_url: str,128- proxy_headers: dict = None,129- verify: VerifyTypes = True,130- cert: CertTypes = None,131- trust_env: bool = None,132- pool_connections: int = 10,133- pool_maxsize: int = 10,134- pool_block: bool = False,135- ):136- assert (137- urllib3 is not None138- ), "urllib3 must be installed in order to use URLLib3ProxyTransport"139-140- self.pool = urllib3.ProxyManager(141- proxy_url=proxy_url,142- proxy_headers=proxy_headers,143- ssl_context=create_ssl_context(144- verify=verify, cert=cert, trust_env=trust_env, http2=False145- ),146- num_pools=pool_connections,147- maxsize=pool_maxsize,148- block=pool_block,149- )modified:httpx/__init__.py-3 removed
36 unmodified lines37 )38 from ._models import URL, Cookies, Headers, QueryParams, Request, Response39 from ._status_codes import StatusCode, codes40 from ._transports.asgi import ASGITransport41-from ._transports.urllib3 import URLLib3ProxyTransport, URLLib3Transport41 from ._transports.wsgi import WSGITransport42 43 __all__ = [44 "__description__",54 unmodified lines99 "TooManyRedirects",100 "TransportError",101 "UnsupportedProtocol",102 "URL",104- "URLLib3ProxyTransport",105- "URLLib3Transport",103 "WriteError",104 "WriteTimeout",105 "WSGITransport",106 ]6 unmodified linesmodified:scripts/coverage+1 added-1 removed
6 unmodified lines7 export SOURCE_FILES="httpx tests"8 9 set -x10 11-${PREFIX}coverage report --omit=httpx/_transports/urllib3.py --show-missing --skip-covered --fail-under=10011+${PREFIX}coverage report --show-missing --skip-covered --fail-under=100modified:README.md-1 removed
120 unmodified lines121 * `chardet` - Fallback auto-detection for response encoding.122 * `rfc3986` - URL parsing & normalization.123 * `idna` - Internationalized domain name support.124 * `sniffio` - Async library autodetection.125-* `urllib3` - Support for the `httpx.URLLib3Transport` class. *(Optional)*125 * `brotlipy` - Decoding for "brotli" compressed responses. *(Optional)*126 127 A huge amount of credit is due to `requests` for the API layout that128 much of this work follows, as well as to `urllib3` for plenty of design4 unmodified lines