Skip to content
Myr

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

8 files+25 added−160 removed

modified:docs/advanced.md+8 added-5 removed
807 unmodified lines
808HTTPX's `Client` also accepts a `transport` argument. This argument allows you809to provide a custom Transport object that will be used to perform the actual810sending of the requests.811812### Usage813814For some advanced configuration you might need to instantiate a transport815class directly, and pass it to the client instance. The `httpcore` package816provides a `local_address` configuration that is only available via this817low-level API.
33 unmodified lines
851do not include any default values for configuring aspects such as the852connection pooling details, so you'll need to provide more explicit853configuration when using this API.854853HTTPX also currently ships with a transport that uses the excellent854[`urllib3` library](https://urllib3.readthedocs.io/en/latest/), which can be855used with the sync `Client`...855### urllib3 transport856857This [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`...858859```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```866864Note that you'll need to install the `urllib3` package to use `URLLib3Transport`.867### Writing custom transports868869A transport instance must implement the Transport API defined by870[`httpcore`](https://www.encode.io/httpcore/api/). You871should either subclass `httpcore.AsyncHTTPTransport` to implement a transport to
32 unmodified lines
modified:docs/compatibility.md+6 added
modified:docs/index.md-1 removed
112 unmodified lines
113* `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)*118119A huge amount of credit is due to `requests` for the API layout that120much of this work follows, as well as to `urllib3` for plenty of design
25 unmodified lines
modified:docs/third-party-packages.md+10 added
deleted:httpx/_transports/urllib3.py-149 removed
1import socket2from typing import Iterator, List, Mapping, Optional, Tuple34import httpcore56from .._config import create_ssl_context7from .._content_streams import ByteStream, IteratorStream8from .._exceptions import NetworkError, map_exceptions9from .._types import CertTypes, VerifyTypes1011try:12 import urllib313 from urllib3.exceptions import MaxRetryError, SSLError14except ImportError: # pragma: nocover15 urllib3 = None161718class 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"3233 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 )4142 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 timeout5354 urllib3_timeout = urllib3.util.Timeout(55 connect=timeout.get("connect"), read=timeout.get("read")56 )5758 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 None6768 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 )8384 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 )106107 def response_bytes() -> Iterator[bytes]:108 with map_exceptions({socket.error: NetworkError}):109 for chunk in conn.stream(4096, decode_content=False):110 yield chunk111112 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)118119 def close(self) -> None:120 self.pool.clear()121122123class 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"139140 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 lines
37)38from ._models import URL, Cookies, Headers, QueryParams, Request, Response39from ._status_codes import StatusCode, codes40from ._transports.asgi import ASGITransport41from ._transports.urllib3 import URLLib3ProxyTransport, URLLib3Transport41from ._transports.wsgi import WSGITransport4243__all__ = [44 "__description__",
54 unmodified lines
99 "TooManyRedirects",100 "TransportError",101 "UnsupportedProtocol",102 "URL",104 "URLLib3ProxyTransport",105 "URLLib3Transport",103 "WriteError",104 "WriteTimeout",105 "WSGITransport",106]
6 unmodified lines
modified:scripts/coverage+1 added-1 removed
6 unmodified lines
7export SOURCE_FILES="httpx tests"89set -x1011${PREFIX}coverage report --omit=httpx/_transports/urllib3.py --show-missing --skip-covered --fail-under=10011${PREFIX}coverage report --show-missing --skip-covered --fail-under=100
modified:README.md-1 removed
120 unmodified lines
121* `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)*126127A huge amount of credit is due to `requests` for the API layout that128much of this work follows, as well as to `urllib3` for plenty of design
4 unmodified lines