Skip to content
Myr

Transport API (#963)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Deprecate Client arg 'dispatch' and use 'transport' * Remove line in test from coverage * Document custom transports * _dispatch > _transports Also rename *Dispatch classes to *Transport and added aliases * Fix linting issues * Missed one _transports import * Promote URLLib3Transport to public API * Remove duplicate arg doc * Assert that urllib3 is imported to use URLLib3Transport * `AsyncClient`, not asynchronous `Client` * Add warning category to warn calls * Update docs/advanced.md Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Add warn_deprecated utility function * Amend docs references to dispatch * Add concrete implementation example * Clearer transport implementation description

authored by Yeray Diaz Diaz · committed by GitHub · parent ba073c8 · Browse files · 16 files+647 added−502 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: Florimond Manca <florimond.manca@gmail.com>

Diff stats

16 files+647 added−502 removed

  • tests:+8 added−8 removed
  • other:+639 added−494 removed

16 files+647 added−502 removed

modified:docs/advanced.md+56 added-3 removed
171 unmodified lines
172 assert r.status_code == 200173 assert r.text == "Hello World!"174```175176For some more complex cases you might need to customize the WSGI dispatch. This allows you to:176For some more complex cases you might need to customize the WSGI transport. This allows you to:177178* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.179* Mount the WSGI application at a subpath by setting `script_name` (WSGI).180* Use a given client address for requests by setting `remote_addr` (WSGI).
1 unmodified line
182For example:183184```python185# Instantiate a client that makes WSGI requests with a client IP of "1.2.3.4".186dispatch = httpx.WSGIDispatch(app=app, remote_addr="1.2.3.4")187with httpx.Client(dispatch=dispatch, base_url="http://testserver") as client:186transport = httpx.WSGITransport(app=app, remote_addr="1.2.3.4")187with httpx.Client(transport=transport, base_url="http://testserver") as client:188 ...189```190191## Request instances
426 unmodified lines
618>>> r = httpx.get("https://localhost:8000", verify="/tmp/client.pem")619>>> r620Response <200 OK>621```622623## Custom Transports624625HTTPX's `Client` also accepts a `transport` argument. This argument allows you626to provide a custom Transport object that will be used to perform the actual627sending of the requests.628629A transport instance must implement the Transport API defined by630[`httpcore`](https://www.encode.io/httpcore/api/). You631should either subclass `httpcore.AsyncHTTPTransport` to implement a transport to632use with `AsyncClient`, or subclass `httpcore.SyncHTTPTransport` to implement a633transport to use with `Client`.634635For example, HTTPX ships with a transport that uses the excellent636[`urllib3` library](https://urllib3.readthedocs.io/en/latest/):637638```python639>>> import httpx640>>> client = httpx.Client(transport=httpx.URLLib3Transport())641>>> client.get("https://example.org")642<Response [200 OK]>643```644645A complete example of a transport implementation would be:646647```python648import json649650import httpcore651import httpx652653654class JSONEchoTransport(httpcore.SyncHTTPTransport):655 """656 A mock transport that returns a JSON response containing the request body.657 """658659 def request(self, method, url, headers=None, stream=None, timeout=None):660 body = b"".join(stream).decode("utf-8")661 content = json.dumps({"body": body}).encode("utf-8")662 stream = httpcore.SyncByteStream([content])663 headers = [(b"content-type", b"application/json")]664 return b"HTTP/1.1", 200, b"OK", headers, stream665```666667Which we can use in the same way:668669```python670>>> client = httpx.Client(transport=JSONEchoTransport())671>>> response = client.post("https://httpbin.org/post", data="Hello, world!")672>>> response.json()673{'body': 'Hello, world!'}674```
modified:docs/async.md+3 added-3 removed
163 unmodified lines
164... assert r.status_code == 200165... assert r.text == "Hello World!"166```167168For some more complex cases you might need to customise the ASGI dispatch. This allows you to:168For some more complex cases you might need to customise the ASGI transport. This allows you to:169170* Inspect 500 error responses rather than raise exceptions by setting `raise_app_exceptions=False`.171* Mount the ASGI application at a subpath by setting `root_path`.172* Use a given client address for requests by setting `client`.
2 unmodified lines
175176```python177# Instantiate a client that makes ASGI requests with a client IP of "1.2.3.4",178# on port 123.179dispatch = httpx.ASGIDispatch(app=app, client=("1.2.3.4", 123))180async with httpx.AsyncClient(dispatch=dispatch, base_url="http://testserver") as client:179transport = httpx.ASGITransport(app=app, client=("1.2.3.4", 123))180async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:181 ...182```183184See [the ASGI documentation](https://asgi.readthedocs.io/en/latest/specs/www.html#connection-scope) for more details on the `client` and `root_path` keys.
17 unmodified lines
deleted:httpx/_dispatch/__init__.py
deleted:httpx/_dispatch/asgi.py-155 removed
1import typing2from typing import Callable, Dict, List, Optional, Tuple34import httpcore5import sniffio67from .._content_streams import ByteStream89if typing.TYPE_CHECKING: # pragma: no cover10 import asyncio11 import trio1213 Event = typing.Union[asyncio.Event, trio.Event]141516def create_event() -> "Event":17 if sniffio.current_async_library() == "trio":18 import trio1920 return trio.Event()21 else:22 import asyncio2324 return asyncio.Event()252627class ASGIDispatch(httpcore.AsyncHTTPTransport):28 """29 A custom AsyncDispatcher that handles sending requests directly to an ASGI app.30 The simplest way to use this functionality is to use the `app` argument.3132 ```33 client = httpx.AsyncClient(app=app)34 ```3536 Alternatively, you can setup the dispatch instance explicitly.37 This allows you to include any additional configuration arguments specific38 to the ASGIDispatch class:3940 ```41 dispatch = httpx.ASGIDispatch(42 app=app,43 root_path="/submount",44 client=("1.2.3.4", 123)45 )46 client = httpx.AsyncClient(dispatch=dispatch)47 ```4849 Arguments:5051 * `app` - The ASGI application.52 * `raise_app_exceptions` - Boolean indicating if exceptions in the application53 should be raised. Default to `True`. Can be set to `False` for use cases54 such as testing the content of a client 500 response.55 * `root_path` - The root path on which the ASGI application should be mounted.56 * `client` - A two-tuple indicating the client IP and port of incoming requests.57 ```58 """5960 def __init__(61 self,62 app: Callable,63 raise_app_exceptions: bool = True,64 root_path: str = "",65 client: Tuple[str, int] = ("127.0.0.1", 123),66 ) -> None:67 self.app = app68 self.raise_app_exceptions = raise_app_exceptions69 self.root_path = root_path70 self.client = client7172 async def request(73 self,74 method: bytes,75 url: Tuple[bytes, bytes, int, bytes],76 headers: List[Tuple[bytes, bytes]] = None,77 stream: httpcore.AsyncByteStream = None,78 timeout: Dict[str, Optional[float]] = None,79 ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream]:80 scheme, host, port, full_path = url81 path, _, query = full_path.partition(b"?")82 scope = {83 "type": "http",84 "asgi": {"version": "3.0"},85 "http_version": "1.1",86 "method": method.decode(),87 "headers": headers,88 "scheme": scheme.decode("ascii"),89 "path": path.decode("ascii"),90 "query_string": query,91 "server": (host.decode("ascii"), port),92 "client": self.client,93 "root_path": self.root_path,94 }95 status_code = None96 response_headers = None97 body_parts = []98 request_complete = False99 response_started = False100 response_complete = create_event()101102 headers = [] if headers is None else headers103 stream = ByteStream(b"") if stream is None else stream104105 request_body_chunks = stream.__aiter__()106107 async def receive() -> dict:108 nonlocal request_complete, response_complete109110 if request_complete:111 await response_complete.wait()112 return {"type": "http.disconnect"}113114 try:115 body = await request_body_chunks.__anext__()116 except StopAsyncIteration:117 request_complete = True118 return {"type": "http.request", "body": b"", "more_body": False}119 return {"type": "http.request", "body": body, "more_body": True}120121 async def send(message: dict) -> None:122 nonlocal status_code, response_headers, body_parts123 nonlocal response_started, response_complete124125 if message["type"] == "http.response.start":126 assert not response_started127128 status_code = message["status"]129 response_headers = message.get("headers", [])130 response_started = True131132 elif message["type"] == "http.response.body":133 assert not response_complete.is_set()134 body = message.get("body", b"")135 more_body = message.get("more_body", False)136137 if body and method != b"HEAD":138 body_parts.append(body)139140 if not more_body:141 response_complete.set()142143 try:144 await self.app(scope, receive, send)145 except Exception:146 if self.raise_app_exceptions or not response_complete:147 raise148149 assert response_complete.is_set()150 assert status_code is not None151 assert response_headers is not None152153 stream = ByteStream(b"".join(body_parts))154155 return (b"HTTP/1.1", status_code, b"", response_headers, stream)
deleted:httpx/_dispatch/urllib3.py-155 removed
1import math2import socket3import ssl4from typing import Dict, Iterator, List, Optional, Tuple, Union56import httpcore7import urllib38from urllib3.exceptions import MaxRetryError, SSLError910from .._config import DEFAULT_POOL_LIMITS, PoolLimits, Proxy, SSLConfig11from .._content_streams import ByteStream, IteratorStream12from .._types import CertTypes, VerifyTypes13from .._utils import as_network_error141516class URLLib3Dispatcher(httpcore.SyncHTTPTransport):17 def __init__(18 self,19 *,20 proxy: Proxy = None,21 verify: VerifyTypes = True,22 cert: CertTypes = None,23 trust_env: bool = None,24 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,25 ):26 ssl_config = SSLConfig(27 verify=verify, cert=cert, trust_env=trust_env, http2=False28 )29 hard_limit = pool_limits.hard_limit30 soft_limit = pool_limits.soft_limit3132 # Our connection pool configuration doesn't quite match up with urllib3's33 # controls, but we can put sensible mappings in place:34 if hard_limit is None:35 block = False36 if soft_limit is None:37 num_pools = 100038 maxsize = 100039 else:40 num_pools = int(math.sqrt(soft_limit))41 maxsize = int(math.sqrt(soft_limit))42 else:43 block = True44 num_pools = int(math.sqrt(hard_limit))45 maxsize = int(math.sqrt(hard_limit))4647 self.pool = self.init_pool_manager(48 proxy=proxy,49 ssl_context=ssl_config.ssl_context,50 num_pools=num_pools,51 maxsize=maxsize,52 block=block,53 )5455 def init_pool_manager(56 self,57 proxy: Optional[Proxy],58 ssl_context: ssl.SSLContext,59 num_pools: int,60 maxsize: int,61 block: bool,62 ) -> Union[urllib3.PoolManager, urllib3.ProxyManager]:63 if proxy is None:64 return urllib3.PoolManager(65 ssl_context=ssl_context,66 num_pools=num_pools,67 maxsize=maxsize,68 block=block,69 )70 else:71 return urllib3.ProxyManager(72 proxy_url=str(proxy.url),73 proxy_headers=dict(proxy.headers),74 ssl_context=ssl_context,75 num_pools=num_pools,76 maxsize=maxsize,77 block=block,78 )7980 def request(81 self,82 method: bytes,83 url: Tuple[bytes, bytes, int, bytes],84 headers: List[Tuple[bytes, bytes]] = None,85 stream: httpcore.SyncByteStream = None,86 timeout: Dict[str, Optional[float]] = None,87 ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.SyncByteStream]:88 headers = [] if headers is None else headers89 stream = ByteStream(b"") if stream is None else stream90 timeout = {} if timeout is None else timeout9192 urllib3_timeout = urllib3.util.Timeout(93 connect=timeout.get("connect"), read=timeout.get("read")94 )9596 chunked = False97 content_length = 098 for header_key, header_value in headers:99 header_key = header_key.lower()100 if header_key == b"transfer-encoding":101 chunked = header_value == b"chunked"102 if header_key == b"content-length":103 content_length = int(header_value.decode("ascii"))104 body = stream if chunked or content_length else None105106 scheme, host, port, path = url107 default_scheme = {80: b"http", 443: "https"}.get(port)108 if scheme == default_scheme:109 url_str = "%s://%s%s" % (110 scheme.decode("ascii"),111 host.decode("ascii"),112 path.decode("ascii"),113 )114 else:115 url_str = "%s://%s:%d%s" % (116 scheme.decode("ascii"),117 host.decode("ascii"),118 port,119 path.decode("ascii"),120 )121122 with as_network_error(MaxRetryError, SSLError, socket.error):123 conn = self.pool.urlopen(124 method=method.decode(),125 url=url_str,126 headers=dict(127 [128 (key.decode("ascii"), value.decode("ascii"))129 for key, value in headers130 ]131 ),132 body=body,133 redirect=False,134 assert_same_host=False,135 retries=0,136 preload_content=False,137 chunked=chunked,138 timeout=urllib3_timeout,139 pool_timeout=timeout.get("pool"),140 )141142 def response_bytes() -> Iterator[bytes]:143 with as_network_error(socket.error):144 for chunk in conn.stream(4096, decode_content=False):145 yield chunk146147 status_code = conn.status148 headers = list(conn.headers.items())149 response_stream = IteratorStream(150 iterator=response_bytes(), close_func=conn.release_conn151 )152 return (b"HTTP/1.1", status_code, conn.reason, headers, response_stream)153154 def close(self) -> None:155 self.pool.clear()
deleted:httpx/_dispatch/wsgi.py-133 removed
1import io2import itertools3import typing45import httpcore67from .._content_streams import ByteStream, IteratorStream8910def _skip_leading_empty_chunks(body: typing.Iterable) -> typing.Iterable:11 body = iter(body)12 for chunk in body:13 if chunk:14 return itertools.chain([chunk], body)15 return []161718class WSGIDispatch(httpcore.SyncHTTPTransport):19 """20 A custom transport that handles sending requests directly to an WSGI app.21 The simplest way to use this functionality is to use the `app` argument.2223 ```24 client = httpx.Client(app=app)25 ```2627 Alternatively, you can setup the dispatch instance explicitly.28 This allows you to include any additional configuration arguments specific29 to the WSGIDispatch class:3031 ```32 dispatch = httpx.WSGIDispatch(33 app=app,34 script_name="/submount",35 remote_addr="1.2.3.4"36 )37 client = httpx.Client(dispatch=dispatch)38 ```3940 Arguments:4142 * `app` - The ASGI application.43 * `raise_app_exceptions` - Boolean indicating if exceptions in the application44 should be raised. Default to `True`. Can be set to `False` for use cases45 such as testing the content of a client 500 response.46 * `script_name` - The root path on which the ASGI application should be mounted.47 * `remote_addr` - A string indicating the client IP of incoming requests.48 ```49 """5051 def __init__(52 self,53 app: typing.Callable,54 raise_app_exceptions: bool = True,55 script_name: str = "",56 remote_addr: str = "127.0.0.1",57 ) -> None:58 self.app = app59 self.raise_app_exceptions = raise_app_exceptions60 self.script_name = script_name61 self.remote_addr = remote_addr6263 def request(64 self,65 method: bytes,66 url: typing.Tuple[bytes, bytes, int, bytes],67 headers: typing.List[typing.Tuple[bytes, bytes]] = None,68 stream: httpcore.SyncByteStream = None,69 timeout: typing.Dict[str, typing.Optional[float]] = None,70 ) -> typing.Tuple[71 bytes,72 int,73 bytes,74 typing.List[typing.Tuple[bytes, bytes]],75 httpcore.SyncByteStream,76 ]:77 headers = [] if headers is None else headers78 stream = ByteStream(b"") if stream is None else stream7980 scheme, host, port, full_path = url81 path, _, query = full_path.partition(b"?")82 environ = {83 "wsgi.version": (1, 0),84 "wsgi.url_scheme": scheme.decode("ascii"),85 "wsgi.input": io.BytesIO(b"".join([chunk for chunk in stream])),86 "wsgi.errors": io.BytesIO(),87 "wsgi.multithread": True,88 "wsgi.multiprocess": False,89 "wsgi.run_once": False,90 "REQUEST_METHOD": method.decode(),91 "SCRIPT_NAME": self.script_name,92 "PATH_INFO": path.decode("ascii"),93 "QUERY_STRING": query.decode("ascii"),94 "SERVER_NAME": host.decode("ascii"),95 "SERVER_PORT": str(port),96 "REMOTE_ADDR": self.remote_addr,97 }98 for header_key, header_value in headers:99 key = header_key.decode("ascii").upper().replace("-", "_")100 if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):101 key = "HTTP_" + key102 environ[key] = header_value.decode("ascii")103104 seen_status = None105 seen_response_headers = None106 seen_exc_info = None107108 def start_response(109 status: str, response_headers: list, exc_info: typing.Any = None110 ) -> None:111 nonlocal seen_status, seen_response_headers, seen_exc_info112 seen_status = status113 seen_response_headers = response_headers114 seen_exc_info = exc_info115116 result = self.app(environ, start_response)117 # This is needed because the status returned by start_response118 # shouldn't be used until the first non-empty chunk has been served.119 result = _skip_leading_empty_chunks(result)120121 assert seen_status is not None122 assert seen_response_headers is not None123 if seen_exc_info and self.raise_app_exceptions:124 raise seen_exc_info[1]125126 status_code = int(seen_status.split()[0])127 headers = [128 (key.encode("ascii"), value.encode("ascii"))129 for key, value in seen_response_headers130 ]131 stream = IteratorStream(chunk for chunk in result)132133 return (b"HTTP/1.1", status_code, b"", headers, stream)
added:httpx/_transports/__init__.py
added:httpx/_transports/asgi.py+173 added
1import typing2from typing import Callable, Dict, List, Optional, Tuple34import httpcore5import sniffio67from .._content_streams import ByteStream8from .._utils import warn_deprecated910if typing.TYPE_CHECKING: # pragma: no cover11 import asyncio12 import trio1314 Event = typing.Union[asyncio.Event, trio.Event]151617def create_event() -> "Event":18 if sniffio.current_async_library() == "trio":19 import trio2021 return trio.Event()22 else:23 import asyncio2425 return asyncio.Event()262728class ASGITransport(httpcore.AsyncHTTPTransport):29 """30 A custom AsyncTransport that handles sending requests directly to an ASGI app.31 The simplest way to use this functionality is to use the `app` argument.3233 ```34 client = httpx.AsyncClient(app=app)35 ```3637 Alternatively, you can setup the dispatch instance explicitly.38 This allows you to include any additional configuration arguments specific39 to the ASGITransport class:4041 ```42 dispatch = httpx.ASGITransport(43 app=app,44 root_path="/submount",45 client=("1.2.3.4", 123)46 )47 client = httpx.AsyncClient(dispatch=dispatch)48 ```4950 Arguments:5152 * `app` - The ASGI application.53 * `raise_app_exceptions` - Boolean indicating if exceptions in the application54 should be raised. Default to `True`. Can be set to `False` for use cases55 such as testing the content of a client 500 response.56 * `root_path` - The root path on which the ASGI application should be mounted.57 * `client` - A two-tuple indicating the client IP and port of incoming requests.58 ```59 """6061 def __init__(62 self,63 app: Callable,64 raise_app_exceptions: bool = True,65 root_path: str = "",66 client: Tuple[str, int] = ("127.0.0.1", 123),67 ) -> None:68 self.app = app69 self.raise_app_exceptions = raise_app_exceptions70 self.root_path = root_path71 self.client = client7273 async def request(74 self,75 method: bytes,76 url: Tuple[bytes, bytes, int, bytes],77 headers: List[Tuple[bytes, bytes]] = None,78 stream: httpcore.AsyncByteStream = None,79 timeout: Dict[str, Optional[float]] = None,80 ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream]:81 scheme, host, port, full_path = url82 path, _, query = full_path.partition(b"?")83 scope = {84 "type": "http",85 "asgi": {"version": "3.0"},86 "http_version": "1.1",87 "method": method.decode(),88 "headers": headers,89 "scheme": scheme.decode("ascii"),90 "path": path.decode("ascii"),91 "query_string": query,92 "server": (host.decode("ascii"), port),93 "client": self.client,94 "root_path": self.root_path,95 }96 status_code = None97 response_headers = None98 body_parts = []99 request_complete = False100 response_started = False101 response_complete = create_event()102103 headers = [] if headers is None else headers104 stream = ByteStream(b"") if stream is None else stream105106 request_body_chunks = stream.__aiter__()107108 async def receive() -> dict:109 nonlocal request_complete, response_complete110111 if request_complete:112 await response_complete.wait()113 return {"type": "http.disconnect"}114115 try:116 body = await request_body_chunks.__anext__()117 except StopAsyncIteration:118 request_complete = True119 return {"type": "http.request", "body": b"", "more_body": False}120 return {"type": "http.request", "body": body, "more_body": True}121122 async def send(message: dict) -> None:123 nonlocal status_code, response_headers, body_parts124 nonlocal response_started, response_complete125126 if message["type"] == "http.response.start":127 assert not response_started128129 status_code = message["status"]130 response_headers = message.get("headers", [])131 response_started = True132133 elif message["type"] == "http.response.body":134 assert not response_complete.is_set()135 body = message.get("body", b"")136 more_body = message.get("more_body", False)137138 if body and method != b"HEAD":139 body_parts.append(body)140141 if not more_body:142 response_complete.set()143144 try:145 await self.app(scope, receive, send)146 except Exception:147 if self.raise_app_exceptions or not response_complete:148 raise149150 assert response_complete.is_set()151 assert status_code is not None152 assert response_headers is not None153154 stream = ByteStream(b"".join(body_parts))155156 return (b"HTTP/1.1", status_code, b"", response_headers, stream)157158159class ASGIDispatch(ASGITransport):160 def __init__(161 self,162 app: Callable,163 raise_app_exceptions: bool = True,164 root_path: str = "",165 client: Tuple[str, int] = ("127.0.0.1", 123),166 ) -> None:167 warn_deprecated("ASGIDispatch is deprecated, please use ASGITransport")168 super().__init__(169 app=app,170 raise_app_exceptions=raise_app_exceptions,171 root_path=root_path,172 client=client,173 )
added:httpx/_transports/urllib3.py+183 added
1import math2import socket3import ssl4from typing import Dict, Iterator, List, Optional, Tuple, Union56import httpcore78from .._config import DEFAULT_POOL_LIMITS, PoolLimits, Proxy, SSLConfig9from .._content_streams import ByteStream, IteratorStream10from .._types import CertTypes, VerifyTypes11from .._utils import as_network_error, warn_deprecated1213try:14 import urllib315 from urllib3.exceptions import MaxRetryError, SSLError16except ImportError: # pragma: nocover17 urllib3 = None181920class URLLib3Transport(httpcore.SyncHTTPTransport):21 def __init__(22 self,23 *,24 proxy: Proxy = None,25 verify: VerifyTypes = True,26 cert: CertTypes = None,27 trust_env: bool = None,28 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,29 ):30 assert (31 urllib3 is not None32 ), "urllib3 must be installed separately in order to use URLLib3Transport"3334 ssl_config = SSLConfig(35 verify=verify, cert=cert, trust_env=trust_env, http2=False36 )37 hard_limit = pool_limits.hard_limit38 soft_limit = pool_limits.soft_limit3940 # Our connection pool configuration doesn't quite match up with urllib3's41 # controls, but we can put sensible mappings in place:42 if hard_limit is None:43 block = False44 if soft_limit is None:45 num_pools = 100046 maxsize = 100047 else:48 num_pools = int(math.sqrt(soft_limit))49 maxsize = int(math.sqrt(soft_limit))50 else:51 block = True52 num_pools = int(math.sqrt(hard_limit))53 maxsize = int(math.sqrt(hard_limit))5455 self.pool = self.init_pool_manager(56 proxy=proxy,57 ssl_context=ssl_config.ssl_context,58 num_pools=num_pools,59 maxsize=maxsize,60 block=block,61 )6263 def init_pool_manager(64 self,65 proxy: Optional[Proxy],66 ssl_context: ssl.SSLContext,67 num_pools: int,68 maxsize: int,69 block: bool,70 ) -> Union[urllib3.PoolManager, urllib3.ProxyManager]:71 if proxy is None:72 return urllib3.PoolManager(73 ssl_context=ssl_context,74 num_pools=num_pools,75 maxsize=maxsize,76 block=block,77 )78 else:79 return urllib3.ProxyManager(80 proxy_url=str(proxy.url),81 proxy_headers=dict(proxy.headers),82 ssl_context=ssl_context,83 num_pools=num_pools,84 maxsize=maxsize,85 block=block,86 )8788 def request(89 self,90 method: bytes,91 url: Tuple[bytes, bytes, int, bytes],92 headers: List[Tuple[bytes, bytes]] = None,93 stream: httpcore.SyncByteStream = None,94 timeout: Dict[str, Optional[float]] = None,95 ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.SyncByteStream]:96 headers = [] if headers is None else headers97 stream = ByteStream(b"") if stream is None else stream98 timeout = {} if timeout is None else timeout99100 urllib3_timeout = urllib3.util.Timeout(101 connect=timeout.get("connect"), read=timeout.get("read")102 )103104 chunked = False105 content_length = 0106 for header_key, header_value in headers:107 header_key = header_key.lower()108 if header_key == b"transfer-encoding":109 chunked = header_value == b"chunked"110 if header_key == b"content-length":111 content_length = int(header_value.decode("ascii"))112 body = stream if chunked or content_length else None113114 scheme, host, port, path = url115 default_scheme = {80: b"http", 443: "https"}.get(port)116 if scheme == default_scheme:117 url_str = "%s://%s%s" % (118 scheme.decode("ascii"),119 host.decode("ascii"),120 path.decode("ascii"),121 )122 else:123 url_str = "%s://%s:%d%s" % (124 scheme.decode("ascii"),125 host.decode("ascii"),126 port,127 path.decode("ascii"),128 )129130 with as_network_error(MaxRetryError, SSLError, socket.error):131 conn = self.pool.urlopen(132 method=method.decode(),133 url=url_str,134 headers=dict(135 [136 (key.decode("ascii"), value.decode("ascii"))137 for key, value in headers138 ]139 ),140 body=body,141 redirect=False,142 assert_same_host=False,143 retries=0,144 preload_content=False,145 chunked=chunked,146 timeout=urllib3_timeout,147 pool_timeout=timeout.get("pool"),148 )149150 def response_bytes() -> Iterator[bytes]:151 with as_network_error(socket.error):152 for chunk in conn.stream(4096, decode_content=False):153 yield chunk154155 status_code = conn.status156 headers = list(conn.headers.items())157 response_stream = IteratorStream(158 iterator=response_bytes(), close_func=conn.release_conn159 )160 return (b"HTTP/1.1", status_code, conn.reason, headers, response_stream)161162 def close(self) -> None:163 self.pool.clear()164165166class URLLib3Dispatch(URLLib3Transport):167 def __init__(168 self,169 *,170 proxy: Proxy = None,171 verify: VerifyTypes = True,172 cert: CertTypes = None,173 trust_env: bool = None,174 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,175 ):176 warn_deprecated("URLLib3Dispatch is deprecated, please use URLLib3Transport")177 super().__init__(178 proxy=proxy,179 verify=verify,180 cert=cert,181 trust_env=trust_env,182 pool_limits=pool_limits,183 )
added:httpx/_transports/wsgi.py+151 added
1import io2import itertools3import typing45import httpcore67from .._content_streams import ByteStream, IteratorStream8from .._utils import warn_deprecated91011def _skip_leading_empty_chunks(body: typing.Iterable) -> typing.Iterable:12 body = iter(body)13 for chunk in body:14 if chunk:15 return itertools.chain([chunk], body)16 return []171819class WSGITransport(httpcore.SyncHTTPTransport):20 """21 A custom transport that handles sending requests directly to an WSGI app.22 The simplest way to use this functionality is to use the `app` argument.2324 ```25 client = httpx.Client(app=app)26 ```2728 Alternatively, you can setup the dispatch instance explicitly.29 This allows you to include any additional configuration arguments specific30 to the WSGITransport class:3132 ```33 dispatch = httpx.WSGITransport(34 app=app,35 script_name="/submount",36 remote_addr="1.2.3.4"37 )38 client = httpx.Client(dispatch=dispatch)39 ```4041 Arguments:4243 * `app` - The ASGI application.44 * `raise_app_exceptions` - Boolean indicating if exceptions in the application45 should be raised. Default to `True`. Can be set to `False` for use cases46 such as testing the content of a client 500 response.47 * `script_name` - The root path on which the ASGI application should be mounted.48 * `remote_addr` - A string indicating the client IP of incoming requests.49 ```50 """5152 def __init__(53 self,54 app: typing.Callable,55 raise_app_exceptions: bool = True,56 script_name: str = "",57 remote_addr: str = "127.0.0.1",58 ) -> None:59 self.app = app60 self.raise_app_exceptions = raise_app_exceptions61 self.script_name = script_name62 self.remote_addr = remote_addr6364 def request(65 self,66 method: bytes,67 url: typing.Tuple[bytes, bytes, int, bytes],68 headers: typing.List[typing.Tuple[bytes, bytes]] = None,69 stream: httpcore.SyncByteStream = None,70 timeout: typing.Dict[str, typing.Optional[float]] = None,71 ) -> typing.Tuple[72 bytes,73 int,74 bytes,75 typing.List[typing.Tuple[bytes, bytes]],76 httpcore.SyncByteStream,77 ]:78 headers = [] if headers is None else headers79 stream = ByteStream(b"") if stream is None else stream8081 scheme, host, port, full_path = url82 path, _, query = full_path.partition(b"?")83 environ = {84 "wsgi.version": (1, 0),85 "wsgi.url_scheme": scheme.decode("ascii"),86 "wsgi.input": io.BytesIO(b"".join([chunk for chunk in stream])),87 "wsgi.errors": io.BytesIO(),88 "wsgi.multithread": True,89 "wsgi.multiprocess": False,90 "wsgi.run_once": False,91 "REQUEST_METHOD": method.decode(),92 "SCRIPT_NAME": self.script_name,93 "PATH_INFO": path.decode("ascii"),94 "QUERY_STRING": query.decode("ascii"),95 "SERVER_NAME": host.decode("ascii"),96 "SERVER_PORT": str(port),97 "REMOTE_ADDR": self.remote_addr,98 }99 for header_key, header_value in headers:100 key = header_key.decode("ascii").upper().replace("-", "_")101 if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):102 key = "HTTP_" + key103 environ[key] = header_value.decode("ascii")104105 seen_status = None106 seen_response_headers = None107 seen_exc_info = None108109 def start_response(110 status: str, response_headers: list, exc_info: typing.Any = None111 ) -> None:112 nonlocal seen_status, seen_response_headers, seen_exc_info113 seen_status = status114 seen_response_headers = response_headers115 seen_exc_info = exc_info116117 result = self.app(environ, start_response)118 # This is needed because the status returned by start_response119 # shouldn't be used until the first non-empty chunk has been served.120 result = _skip_leading_empty_chunks(result)121122 assert seen_status is not None123 assert seen_response_headers is not None124 if seen_exc_info and self.raise_app_exceptions:125 raise seen_exc_info[1]126127 status_code = int(seen_status.split()[0])128 headers = [129 (key.encode("ascii"), value.encode("ascii"))130 for key, value in seen_response_headers131 ]132 stream = IteratorStream(chunk for chunk in result)133134 return (b"HTTP/1.1", status_code, b"", headers, stream)135136137class WSGIDispatch(WSGITransport):138 def __init__(139 self,140 app: typing.Callable,141 raise_app_exceptions: bool = True,142 script_name: str = "",143 remote_addr: str = "127.0.0.1",144 ) -> None:145 warn_deprecated("WSGIDispatch is deprecated, please use WSGITransport")146 super().__init__(147 app=app,148 raise_app_exceptions=raise_app_exceptions,149 script_name=script_name,150 remote_addr=remote_addr,151 )
modified:httpx/__init__.py+6 added-2 removed
1 unmodified line
2from ._api import delete, get, head, options, patch, post, put, request, stream3from ._auth import Auth, BasicAuth, DigestAuth4from ._client import AsyncClient, Client5from ._config import PoolLimits, Proxy, Timeout6from ._dispatch.asgi import ASGIDispatch7from ._dispatch.wsgi import WSGIDispatch6from ._exceptions import (7 ConnectTimeout,8 CookieConflict,9 DecodingError,
14 unmodified lines
24 WriteTimeout,25)26from ._models import URL, Cookies, Headers, QueryParams, Request, Response27from ._status_codes import StatusCode, codes28from ._transports.asgi import ASGIDispatch, ASGITransport29from ._transports.urllib3 import URLLib3Transport30from ._transports.wsgi import WSGIDispatch, WSGITransport3132__all__ = [33 "__description__",34 "__title__",
9 unmodified lines
44 "request",45 "stream",46 "codes",47 "ASGIDispatch",48 "ASGITransport",49 "AsyncClient",50 "Auth",51 "BasicAuth",52 "Client",
19 unmodified lines
72 "ProxyError",73 "TooManyRedirects",74 "WriteTimeout",75 "URL",76 "URLLib3Transport",77 "StatusCode",78 "Cookies",79 "Headers",80 "QueryParams",81 "Request",82 "Response",83 "DigestAuth",84 "WSGIDispatch",85 "WSGITransport",86]
modified:httpx/_client.py+59 added-38 removed
16 unmodified lines
17 Timeout,18 UnsetType,19)20from ._content_streams import ContentStream21from ._dispatch.asgi import ASGIDispatch22from ._dispatch.wsgi import WSGIDispatch21from ._exceptions import HTTPError, InvalidURL, RequestBodyUnavailable, TooManyRedirects22from ._models import URL, Cookies, Headers, Origin, QueryParams, Request, Response23from ._status_codes import codes24from ._transports.asgi import ASGITransport25from ._transports.wsgi import WSGITransport26from ._types import (27 AuthTypes,28 CertTypes,29 CookieTypes,
10 unmodified lines
40 NetRCInfo,41 get_environment_proxies,42 get_logger,43 should_not_be_proxied,44 warn_deprecated,45)4647logger = get_logger(__name__)48
42 unmodified lines
91 proxy = Proxy(url=proxies) if isinstance(proxies, (str, URL)) else proxies92 return {"all": proxy}93 elif isinstance(proxies, httpcore.AsyncHTTPTransport): # pragma: nocover94 raise RuntimeError(94 "Passing a dispatcher instance to 'proxies=' is no longer "95 "Passing a transport instance to 'proxies=' is no longer "96 "supported. Use `httpx.Proxy() instead.`"97 )98 else:99 new_proxies = {}
2 unmodified lines
102 proxy = Proxy(url=value) if isinstance(value, (str, URL)) else value103 new_proxies[str(key)] = proxy104 elif isinstance(value, httpcore.AsyncHTTPTransport): # pragma: nocover105 raise RuntimeError(105 "Passing a dispatcher instance to 'proxies=' is "106 "Passing a transport instance to 'proxies=' is "107 "no longer supported. Use `httpx.Proxy() instead.`"108 )109 return new_proxies110
306 unmodified lines
417 * **max_redirects** - *(optional)* The maximum number of redirect responses418 that should be followed.419 * **base_url** - *(optional)* A URL to use as the base when building420 request URLs.420 * **dispatch** - *(optional)* A dispatch class to use for sending requests421 * **transport** - *(optional)* A transport class to use for sending requests422 over the network.423 * **dispatch** - *(optional)* A deprecated alias for transport.424 * **app** - *(optional)* An WSGI application to send requests to,425 rather than sending actual network requests.426 * **trust_env** - *(optional)* Enables or disables usage of environment427 variables for configuration.
12 unmodified lines
440 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,441 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,442 max_redirects: int = DEFAULT_MAX_REDIRECTS,443 base_url: URLTypes = None,444 transport: httpcore.SyncHTTPTransport = None,445 dispatch: httpcore.SyncHTTPTransport = None,446 app: typing.Callable = None,447 trust_env: bool = True,448 ):
9 unmodified lines
458 )459460 proxy_map = self.get_proxy_map(proxies, trust_env)461459 self.dispatch = self.init_dispatch(462 if dispatch is not None:463 warn_deprecated(464 "The dispatch argument is deprecated since v0.13 and will be "465 "removed in a future release, please use 'transport'"466 )467 if transport is None:468 transport = dispatch469470 self.transport = self.init_transport(471 verify=verify,472 cert=cert,473 pool_limits=pool_limits,463 dispatch=dispatch,474 transport=transport,475 app=app,476 trust_env=trust_env,477 )478 self.proxies: typing.Dict[str, httpcore.SyncHTTPTransport] = {468 key: self.init_proxy_dispatch(479 key: self.init_proxy_transport(480 proxy,481 verify=verify,482 cert=cert,483 pool_limits=pool_limits,
1 unmodified line
485 )486 for key, proxy in proxy_map.items()487 }488478 def init_dispatch(489 def init_transport(490 self,491 verify: VerifyTypes = True,492 cert: CertTypes = None,493 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,483 dispatch: httpcore.SyncHTTPTransport = None,494 transport: httpcore.SyncHTTPTransport = None,495 app: typing.Callable = None,496 trust_env: bool = True,497 ) -> httpcore.SyncHTTPTransport:487 if dispatch is not None:488 return dispatch498 if transport is not None:499 return transport500501 if app is not None:491 return WSGIDispatch(app=app)502 return WSGITransport(app=app)503504 ssl_context = SSLConfig(505 verify=verify, cert=cert, trust_env=trust_env506 ).ssl_context
5 unmodified lines
512 max_keepalive=max_keepalive,513 max_connections=max_connections,514 )515505 def init_proxy_dispatch(516 def init_proxy_transport(517 self,518 proxy: Proxy,519 verify: VerifyTypes = True,520 cert: CertTypes = None,
14 unmodified lines
535 max_keepalive=max_keepalive,536 max_connections=max_connections,537 )538528 def dispatcher_for_url(self, url: URL) -> httpcore.SyncHTTPTransport:539 def transport_for_url(self, url: URL) -> httpcore.SyncHTTPTransport:540 """541 Returns the transport instance that should be used for a given URL.542 This will either be the standard connection pool, or a proxy.543 """
11 unmodified lines
555 "all",556 )557 for proxy_key in proxy_keys:558 if proxy_key and proxy_key in self.proxies:548 dispatcher = self.proxies[proxy_key]549 return dispatcher559 transport = self.proxies[proxy_key]560 return transport561551 return self.dispatch562 return self.transport563564 def request(565 self,566 method: str,
123 unmodified lines
690 """691 Sends a single request, without handling any redirections.692 """693683 dispatcher = self.dispatcher_for_url(request.url)694 transport = self.transport_for_url(request.url)695696 try:697 (698 http_version,699 status_code,700 reason_phrase,701 headers,702 stream,692 ) = dispatcher.request(703 ) = transport.request(704 request.method.encode(),705 request.url.raw,706 headers=request.headers.raw,707 stream=request.stream,
194 unmodified lines
902 timeout=timeout,903 )904905 def close(self) -> None:895 self.dispatch.close()906 self.transport.close()907 for proxy in self.proxies.values():908 proxy.close()909910 def __enter__(self) -> "Client":
48 unmodified lines
959 * **max_redirects** - *(optional)* The maximum number of redirect responses960 that should be followed.961 * **base_url** - *(optional)* A URL to use as the base when building962 request URLs.952 * **dispatch** - *(optional)* A dispatch class to use for sending requests963 * **transport** - *(optional)* A transport class to use for sending requests964 over the network.965 * **dispatch** - *(optional)* A deprecated alias for transport.966 * **app** - *(optional)* An ASGI application to send requests to,967 rather than sending actual network requests.968 * **trust_env** - *(optional)* Enables or disables usage of environment969 variables for configuration.
13 unmodified lines
983 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,984 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,985 max_redirects: int = DEFAULT_MAX_REDIRECTS,986 base_url: URLTypes = None,987 transport: httpcore.AsyncHTTPTransport = None,988 dispatch: httpcore.AsyncHTTPTransport = None,989 app: typing.Callable = None,990 trust_env: bool = True,991 ):
7 unmodified lines
999 base_url=base_url,1000 trust_env=trust_env,1001 )10021003 if dispatch is not None:1004 warn_deprecated(1005 "The dispatch argument is deprecated since v0.13 and will be "1006 "removed in a future release, please use 'transport'",1007 )1008 if transport is None:1009 transport = dispatch10101011 proxy_map = self.get_proxy_map(proxies, trust_env)1012992 self.dispatch = self.init_dispatch(1013 self.transport = self.init_transport(1014 verify=verify,1015 cert=cert,1016 http2=http2,1017 pool_limits=pool_limits,997 dispatch=dispatch,1018 transport=transport,1019 app=app,1020 trust_env=trust_env,1021 )1022 self.proxies: typing.Dict[str, httpcore.AsyncHTTPTransport] = {1002 key: self.init_proxy_dispatch(1023 key: self.init_proxy_transport(1024 proxy,1025 verify=verify,1026 cert=cert,1027 http2=http2,
2 unmodified lines
1030 )1031 for key, proxy in proxy_map.items()1032 }10331013 def init_dispatch(1034 def init_transport(1035 self,1036 verify: VerifyTypes = True,1037 cert: CertTypes = None,1038 http2: bool = False,1039 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,1019 dispatch: httpcore.AsyncHTTPTransport = None,1040 transport: httpcore.AsyncHTTPTransport = None,1041 app: typing.Callable = None,1042 trust_env: bool = True,1043 ) -> httpcore.AsyncHTTPTransport:1023 if dispatch is not None:1024 return dispatch1044 if transport is not None:1045 return transport10461047 if app is not None:1027 return ASGIDispatch(app=app)1048 return ASGITransport(app=app)10491050 ssl_context = SSLConfig(1051 verify=verify, cert=cert, trust_env=trust_env1052 ).ssl_context
6 unmodified lines
1059 max_connections=max_connections,1060 http2=http2,1061 )10621042 def init_proxy_dispatch(1063 def init_proxy_transport(1064 self,1065 proxy: Proxy,1066 verify: VerifyTypes = True,1067 cert: CertTypes = None,
16 unmodified lines
1084 max_connections=max_connections,1085 http2=http2,1086 )10871067 def dispatcher_for_url(self, url: URL) -> httpcore.AsyncHTTPTransport:1088 def transport_for_url(self, url: URL) -> httpcore.AsyncHTTPTransport:1089 """1090 Returns the transport instance that should be used for a given URL.1091 This will either be the standard connection pool, or a proxy.1092 """
11 unmodified lines
1104 "all",1105 )1106 for proxy_key in proxy_keys:1107 if proxy_key and proxy_key in self.proxies:1087 dispatcher = self.proxies[proxy_key]1088 return dispatcher1108 transport = self.proxies[proxy_key]1109 return transport11101090 return self.dispatch1111 return self.transport11121113 async def request(1114 self,1115 method: str,
126 unmodified lines
1242 """1243 Sends a single request, without handling any redirections.1244 """12451225 dispatcher = self.dispatcher_for_url(request.url)1246 transport = self.transport_for_url(request.url)12471248 try:1249 (1250 http_version,1251 status_code,1252 reason_phrase,1253 headers,1254 stream,1234 ) = await dispatcher.request(1255 ) = await transport.request(1256 request.method.encode(),1257 request.url.raw,1258 headers=request.headers.raw,1259 stream=request.stream,
194 unmodified lines
1454 timeout=timeout,1455 )14561457 async def aclose(self) -> None:1437 await self.dispatch.aclose()1458 await self.transport.aclose()1459 for proxy in self.proxies.values():1460 await proxy.aclose()14611462 async def __aenter__(self) -> "AsyncClient":
72 unmodified lines
modified:httpx/_models.py+3 added-5 removed
2 unmodified lines
3import email.message4import json as jsonlib5import typing6import urllib.request7import warnings7from collections.abc import MutableMapping8from http.cookiejar import Cookie, CookieJar9from urllib.parse import parse_qsl, urlencode10
39 unmodified lines
50 normalize_header_value,51 obfuscate_sensitive_headers,52 parse_header_links,53 str_query_param,54 warn_deprecated,55)5657if typing.TYPE_CHECKING: # pragma: no cover58 from ._dispatch.base import AsyncDispatcher # noqa: F401
814 unmodified lines
873 return f"<Response [{self.status_code} {self.reason_phrase}]>"874875 @property876 def stream(self): # type: ignore877 warnings.warn( # pragma: nocover877 warn_deprecated( # pragma: nocover878 "Response.stream() is due to be deprecated. "879 "Use Response.aiter_bytes() instead.",880 DeprecationWarning,880 )881 return self.aiter_bytes # pragma: nocover882883 @property884 def raw(self): # type: ignore886 warnings.warn( # pragma: nocover885 warn_deprecated( # pragma: nocover886 "Response.raw() is due to be deprecated. "887 "Use Response.aiter_raw() instead.",889 DeprecationWarning,888 )889 return self.aiter_raw # pragma: nocover890891 def read(self) -> bytes:
309 unmodified lines
modified:httpx/_utils.py+5 added
6 unmodified lines
7import os8import re9import sys10import typing11import warnings12from datetime import timedelta13from pathlib import Path14from time import perf_counter15from types import TracebackType
384 unmodified lines
400 for cls in exception_classes:401 if isinstance(exc, cls):402 raise NetworkError(exc) from exc403 raise404405406def warn_deprecated(message: str) -> None:407 warnings.warn(message, DeprecationWarning)
modified:tests/client/test_auth.py+1 added-1 removed
482 unmodified lines
483 auth = DigestAuth(username="tomchristie", password="password123")484 client = AsyncClient(dispatch=MockDispatch())485486 async def streaming_body():487 yield b"Example request body"487 yield b"Example request body" # pragma: nocover488489 with pytest.raises(RequestBodyUnavailable):490 await client.post(url, data=streaming_body(), auth=auth)491
36 unmodified lines
modified:tests/client/test_proxies.py+7 added-7 removed
72 unmodified lines
73 PROXY_URL + ":2",74 ),75 ],76)77def test_dispatcher_for_request(url, proxies, expected):77def test_transport_for_request(url, proxies, expected):78 client = httpx.AsyncClient(proxies=proxies)79 dispatcher = client.dispatcher_for_url(httpx.URL(url))79 transport = client.transport_for_url(httpx.URL(url))8081 if expected is None:82 assert dispatcher is client.dispatch82 assert transport is client.transport83 else:84 assert dispatcher.proxy_origin == httpx.URL(expected).raw[:3]84 assert transport.proxy_origin == httpx.URL(expected).raw[:3]858687def test_unsupported_proxy_scheme():88 with pytest.raises(ValueError):
20 unmodified lines
109 for name, value in env.items():110 monkeypatch.setenv(name, value)111112 client = httpx.AsyncClient()113 dispatcher = client.dispatcher_for_url(httpx.URL(url))113 transport = client.transport_for_url(httpx.URL(url))114115 if expected is None:116 assert dispatcher == client.dispatch116 assert transport == client.transport117 else:118 assert dispatcher.proxy_origin == httpx.URL(expected).raw[:3]118 assert transport.proxy_origin == httpx.URL(expected).raw[:3]