Transport API (#1522)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Added httpx.BaseTransport and httpx.AsyncBaseTransport * Test coverage and default transports to calling .close on __exit__ * BaseTransport documentation * Use 'handle_request' for the transport API. * Docs tweaks * Docs tweaks * Minor docstring tweak * Transport API docs * Drop 'Optional' on Transport API * Docs tweaks * Tweak CHANGELOG * Drop erronous example.py * Push httpcore exception wrapping out of client into transport (#1524) * Push httpcore exception wrapping out of client into transport * Include close/aclose extensions in docstring * Comment about the request property on RequestError exceptions * Extensions reason_phrase and http_version as bytes (#1526) * Extensions reason_phrase and http_version as bytes * Update BaseTransport docstring * Neaten up our try...except structure for ensuring responses (#1525) * Fix CHANGELOG typo Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Fix CHANGELOG typo Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * stream: Iterator[bytes] -> stream: Iterable[bytes] * Use proper bytestream interfaces when calling into httpcore * Grungy typing workaround due to httpcore using Iterator instead of Iterable in bytestream types * Update docs/advanced.md Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Consistent typing imports across tranports * Update docs/advanced.md Co-authored-by: Florimond Manca <florimond.manca@gmail.com>
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
20 files+625 added−335 removed
- tests:+101 added−70 removed
- other:+524 added−265 removed
Provenance
- Commit
1a6e254- Tree
435f606- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
6cb1672
20 files changed+625 added−335 removed
modified:docs/advanced.md+24 added-17 removed
1013 unmodified lines1014 ```1015 1016 ### Writing custom transports1017 1018-A transport instance must implement the Transport API defined by1019-[`httpcore`](https://www.encode.io/httpcore/api/). You1020-should either subclass `httpcore.AsyncHTTPTransport` to implement a transport to1021-use with `AsyncClient`, or subclass `httpcore.SyncHTTPTransport` to implement a1022-transport to use with `Client`.1018+A transport instance must implement the low-level Transport API, which deals1019+with sending a single request, and returning a response. You should either1020+subclass `httpx.BaseTransport` to implement a transport to use with `Client`,1021+or subclass `httpx.AsyncBaseTransport` to implement a transport to1022+use with `AsyncClient`.1023 1024+At the layer of the transport API we're using plain primitives.1025+No `Request` or `Response` models, no fancy `URL` or `Header` handling.1026+This strict point of cut-off provides a clear design separation between the1027+HTTPX API, and the low-level network handling.1028+1029+See the `handle_request` and `handle_async_request` docstrings for more details1030+on the specifics of the Transport API.1031+1032 A complete example of a custom transport implementation would be:1033 1034 ```python1035 import json1028-import httpcore1036+import httpx1037 1038 1031-class HelloWorldTransport(httpcore.SyncHTTPTransport):1039+class HelloWorldTransport(httpx.BaseTransport):1040 """1041 A mock transport that always returns a JSON "Hello, world!" response.1042 """1043 1036- def request(self, method, url, headers=None, stream=None, ext=None):1044+ def handle_request(self, method, url, headers, stream, extensions):1045 message = {"text": "Hello, world!"}1046 content = json.dumps(message).encode("utf-8")1039- stream = httpcore.PlainByteStream(content)1047+ stream = [content]1048 headers = [(b"content-type", b"application/json")]1041- ext = {"http_version": b"HTTP/1.1"}1042- return 200, headers, stream, ext1049+ extensions = {}1050+ return 200, headers, stream, extensions1051 ```1052 1053 Which we can use in the same way:1054 36 unmodified lines1091 which transport an outgoing request should be routed via, with [the same style1092 used for specifying proxy routing](#routing).1093 1094 ```python1087-import httpcore1095 import httpx1096 1090-class HTTPSRedirectTransport(httpcore.SyncHTTPTransport):1097+class HTTPSRedirectTransport(httpx.BaseTransport):1098 """1099 A transport that always redirects to HTTPS.1100 """1101 1095- def request(self, method, url, headers=None, stream=None, ext=None):1102+ def handle_request(self, method, url, headers, stream, extensions):1103 scheme, host, port, path = url1104 if port is None:1105 location = b"https://%s%s" % (host, path)1106 else:1107 location = b"https://%s:%d%s" % (host, port, path)1101- stream = httpcore.PlainByteStream(b"")1108+ stream = [b""]1109 headers = [(b"location", location)]1103- ext = {"http_version": b"HTTP/1.1"}1104- return 303, headers, stream, ext1110+ extensions = {}1111+ return 303, headers, stream, extensions1112 1113 1114 # A client where any `http` requests are always redirected to `https`1115 mounts = {'http://': HTTPSRedirectTransport()}34 unmodified linesmodified:httpx/_transports/asgi.py+21 added-19 removed
1-from typing import TYPE_CHECKING, Callable, List, Optional, Tuple, Union1+import typing2 from urllib.parse import unquote3 4-import httpcore4 import sniffio5 6+from .base import AsyncBaseTransport7+7-if TYPE_CHECKING: # pragma: no cover8+if typing.TYPE_CHECKING: # pragma: no cover9 import asyncio10 11 import trio12 12- Event = Union[asyncio.Event, trio.Event]13+ Event = typing.Union[asyncio.Event, trio.Event]14 15 16 def create_event() -> "Event":17 if sniffio.current_async_library() == "trio":5 unmodified lines23 24 return asyncio.Event()25 26 26-class ASGITransport(httpcore.AsyncHTTPTransport):27+class ASGITransport(AsyncBaseTransport):28 """29 A custom AsyncTransport that handles sending requests directly to an ASGI app.30 The simplest way to use this functionality is to use the `app` argument.31 26 unmodified lines58 """59 60 def __init__(61 self,61- app: Callable,62+ app: typing.Callable,63 raise_app_exceptions: bool = True,64 root_path: str = "",64- client: Tuple[str, int] = ("127.0.0.1", 123),65+ client: typing.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 = client71 71- async def arequest(72+ async def handle_async_request(73 self,74 method: bytes,74- url: Tuple[bytes, bytes, Optional[int], bytes],75- headers: List[Tuple[bytes, bytes]] = None,76- stream: httpcore.AsyncByteStream = None,77- ext: dict = None,78- ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]:79- headers = [] if headers is None else headers80- stream = httpcore.PlainByteStream(content=b"") if stream is None else stream81-75+ url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],76+ headers: typing.List[typing.Tuple[bytes, bytes]],77+ stream: typing.AsyncIterable[bytes],78+ extensions: dict,79+ ) -> typing.Tuple[80+ int, typing.List[typing.Tuple[bytes, bytes]], typing.AsyncIterable[bytes], dict81+ ]:82 # ASGI scope.83 scheme, host, port, full_path = url84 path, _, query = full_path.partition(b"?")85 scope = {68 unmodified lines154 assert response_complete.is_set()155 assert status_code is not None156 assert response_headers is not None157 158- stream = httpcore.PlainByteStream(content=b"".join(body_parts))159- ext = {}158+ async def response_stream() -> typing.AsyncIterator[bytes]:159+ yield b"".join(body_parts)160 161+ extensions = {}162+161- return (status_code, response_headers, stream, ext)163+ return (status_code, response_headers, response_stream(), extensions)added:httpx/_transports/base.py+129 added
1+import typing2+from types import TracebackType3+4+T = typing.TypeVar("T", bound="BaseTransport")5+A = typing.TypeVar("A", bound="AsyncBaseTransport")6+7+8+class BaseTransport:9+ def __enter__(self: T) -> T:10+ return self11+12+ def __exit__(13+ self,14+ exc_type: typing.Type[BaseException] = None,15+ exc_value: BaseException = None,16+ traceback: TracebackType = None,17+ ) -> None:18+ self.close()19+20+ def handle_request(21+ self,22+ method: bytes,23+ url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],24+ headers: typing.List[typing.Tuple[bytes, bytes]],25+ stream: typing.Iterable[bytes],26+ extensions: dict,27+ ) -> typing.Tuple[28+ int, typing.List[typing.Tuple[bytes, bytes]], typing.Iterable[bytes], dict29+ ]:30+ """31+ Send a single HTTP request and return a response.32+33+ At this layer of API we're simply using plain primitives. No `Request` or34+ `Response` models, no fancy `URL` or `Header` handling. This strict point35+ of cut-off provides a clear design seperation between the HTTPX API,36+ and the low-level network handling.37+38+ Developers shouldn't typically ever need to call into this API directly,39+ since the Client class provides all the higher level user-facing API40+ niceties.41+42+ Example usage:43+44+ with httpx.HTTPTransport() as transport:45+ status_code, headers, stream, extensions = transport.handle_request(46+ method=b'GET',47+ url=(b'https', b'www.example.com', 443, b'/'),48+ headers=[(b'Host', b'www.example.com')],49+ stream=[],50+ extensions={}51+ )52+ try:53+ body = b''.join([part for part in stream])54+ finally:55+ if 'close' in extensions:56+ extensions['close']()57+ print(status_code, headers, body)58+59+ Arguments:60+61+ method: The request method as bytes. Eg. b'GET'.62+ url: The components of the request URL, as a tuple of `(scheme, host, port, target)`.63+ The target will usually be the URL path, but also allows for alternative64+ formulations, such as proxy requests which include the complete URL in65+ the target portion of the HTTP request, or for "OPTIONS *" requests, which66+ cannot be expressed in a URL string.67+ headers: The request headers as a list of byte pairs.68+ stream: The request body as a bytes iterator.69+ extensions: An open ended dictionary, including optional extensions to the70+ core request/response API. Keys may include:71+ timeout: A dictionary of str:Optional[float] timeout values.72+ May include values for 'connect', 'read', 'write', or 'pool'.73+74+ Returns a tuple of:75+76+ status_code: The response status code as an integer. Should be in the range 1xx-5xx.77+ headers: The response headers as a list of byte pairs.78+ stream: The response body as a bytes iterator.79+ extensions: An open ended dictionary, including optional extensions to the80+ core request/response API. Keys are plain strings, and may include:81+ reason_phrase: The reason-phrase of the HTTP response, as bytes. Eg b'OK'.82+ HTTP/2 onwards does not include a reason phrase on the wire.83+ When no key is included, a default based on the status code may84+ be used. An empty-string reason phrase should not be substituted85+ for a default, as it indicates the server left the portion blank86+ eg. the leading response bytes were b"HTTP/1.1 200 <CRLF>".87+ http_version: The HTTP version, as bytes. Eg. b"HTTP/1.1".88+ When no http_version key is included, HTTP/1.1 may be assumed.89+ close: A callback which should be invoked to release any network90+ resources.91+ aclose: An async callback which should be invoked to release any92+ network resources.93+ """94+ raise NotImplementedError(95+ "The 'handle_request' method must be implemented."96+ ) # pragma: nocover97+98+ def close(self) -> None:99+ pass100+101+102+class AsyncBaseTransport:103+ async def __aenter__(self: A) -> A:104+ return self105+106+ async def __aexit__(107+ self,108+ exc_type: typing.Type[BaseException] = None,109+ exc_value: BaseException = None,110+ traceback: TracebackType = None,111+ ) -> None:112+ await self.aclose()113+114+ async def handle_async_request(115+ self,116+ method: bytes,117+ url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],118+ headers: typing.List[typing.Tuple[bytes, bytes]],119+ stream: typing.AsyncIterable[bytes],120+ extensions: dict,121+ ) -> typing.Tuple[122+ int, typing.List[typing.Tuple[bytes, bytes]], typing.AsyncIterable[bytes], dict123+ ]:124+ raise NotImplementedError(125+ "The 'handle_async_request' method must be implemented."126+ ) # pragma: nocover127+128+ async def aclose(self) -> None:129+ passmodified:httpx/_transports/default.py+136 added-20 removed
22 unmodified lines23 # Using advanced httpcore configuration, with unix domain sockets.24 transport = httpx.HTTPTransport(uds="socket.uds")25 client = httpx.Client(transport=transport)26 """27+import contextlib28 import typing29 from types import TracebackType30 31 import httpcore32 33 from .._config import DEFAULT_LIMITS, Limits, Proxy, create_ssl_context34+from .._exceptions import (35+ CloseError,36+ ConnectError,37+ ConnectTimeout,38+ LocalProtocolError,39+ NetworkError,40+ PoolTimeout,41+ ProtocolError,42+ ProxyError,43+ ReadError,44+ ReadTimeout,45+ RemoteProtocolError,46+ TimeoutException,47+ UnsupportedProtocol,48+ WriteError,49+ WriteTimeout,50+)51 from .._types import CertTypes, VerifyTypes52+from .base import AsyncBaseTransport, BaseTransport53 54 T = typing.TypeVar("T", bound="HTTPTransport")55 A = typing.TypeVar("A", bound="AsyncHTTPTransport")37-Headers = typing.List[typing.Tuple[bytes, bytes]]38-URL = typing.Tuple[bytes, bytes, typing.Optional[int], bytes]56 57 58+@contextlib.contextmanager59+def map_httpcore_exceptions() -> typing.Iterator[None]:60+ try:61+ yield62+ except Exception as exc:63+ mapped_exc = None64+65+ for from_exc, to_exc in HTTPCORE_EXC_MAP.items():66+ if not isinstance(exc, from_exc):67+ continue68+ # We want to map to the most specific exception we can find.69+ # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to70+ # `httpx.ReadTimeout`, not just `httpx.TimeoutException`.71+ if mapped_exc is None or issubclass(to_exc, mapped_exc):72+ mapped_exc = to_exc73+74+ if mapped_exc is None: # pragma: nocover75+ raise76+77+ message = str(exc)78+ raise mapped_exc(message) from exc79+80+81+def ensure_http_version_reason_phrase_as_bytes(extensions: dict) -> None:82+ # From HTTPX 0.18 onwards we're treating the "reason_phrase" and "http_version"83+ # extensions as bytes, in order to be more precise. Also we're using the84+ # "reason_phrase" key in preference to "reason", in order to match properly85+ # with the HTTP spec naming.86+ # HTTPCore 0.12 does not yet use these same conventions for the extensions,87+ # so we bridge between the two styles for now.88+ if "reason" in extensions:89+ extensions["reason_phrase"] = extensions.pop("reason").encode("ascii")90+ if "http_version" in extensions:91+ extensions["http_version"] = extensions["http_version"].encode("ascii")92+93+94+HTTPCORE_EXC_MAP = {95+ httpcore.TimeoutException: TimeoutException,96+ httpcore.ConnectTimeout: ConnectTimeout,97+ httpcore.ReadTimeout: ReadTimeout,98+ httpcore.WriteTimeout: WriteTimeout,99+ httpcore.PoolTimeout: PoolTimeout,100+ httpcore.NetworkError: NetworkError,101+ httpcore.ConnectError: ConnectError,102+ httpcore.ReadError: ReadError,103+ httpcore.WriteError: WriteError,104+ httpcore.CloseError: CloseError,105+ httpcore.ProxyError: ProxyError,106+ httpcore.UnsupportedProtocol: UnsupportedProtocol,107+ httpcore.ProtocolError: ProtocolError,108+ httpcore.LocalProtocolError: LocalProtocolError,109+ httpcore.RemoteProtocolError: RemoteProtocolError,110+}111+112+41-class HTTPTransport(httpcore.SyncHTTPTransport):113+class HTTPTransport(BaseTransport):114 def __init__(115 self,116 verify: VerifyTypes = True,117 cert: CertTypes = None,44 unmodified lines162 traceback: TracebackType = None,163 ) -> None:164 self._pool.__exit__(exc_type, exc_value, traceback)165 94- def request(166+ def handle_request(167 self,168 method: bytes,97- url: URL,98- headers: Headers = None,99- stream: httpcore.SyncByteStream = None,100- ext: dict = None,101- ) -> typing.Tuple[int, Headers, httpcore.SyncByteStream, dict]:102- return self._pool.request(method, url, headers=headers, stream=stream, ext=ext)169+ url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],170+ headers: typing.List[typing.Tuple[bytes, bytes]],171+ stream: typing.Iterable[bytes],172+ extensions: dict,173+ ) -> typing.Tuple[174+ int, typing.List[typing.Tuple[bytes, bytes]], typing.Iterable[bytes], dict175+ ]:176+ with map_httpcore_exceptions():177+ status_code, headers, byte_stream, extensions = self._pool.request(178+ method=method,179+ url=url,180+ headers=headers,181+ stream=httpcore.IteratorByteStream(iter(stream)),182+ ext=extensions,183+ )184 185+ def response_stream() -> typing.Iterator[bytes]:186+ with map_httpcore_exceptions():187+ for part in byte_stream:188+ yield part189+190+ def close() -> None:191+ with map_httpcore_exceptions():192+ byte_stream.close()193+194+ ensure_http_version_reason_phrase_as_bytes(extensions)195+ extensions["close"] = close196+197+ return status_code, headers, response_stream(), extensions198+199 def close(self) -> None:200 self._pool.close()201 202 108-class AsyncHTTPTransport(httpcore.AsyncHTTPTransport):203+class AsyncHTTPTransport(AsyncBaseTransport):204 def __init__(205 self,206 verify: VerifyTypes = True,207 cert: CertTypes = None,44 unmodified lines252 traceback: TracebackType = None,253 ) -> None:254 await self._pool.__aexit__(exc_type, exc_value, traceback)255 161- async def arequest(256+ async def handle_async_request(257 self,258 method: bytes,164- url: URL,165- headers: Headers = None,166- stream: httpcore.AsyncByteStream = None,167- ext: dict = None,168- ) -> typing.Tuple[int, Headers, httpcore.AsyncByteStream, dict]:169- return await self._pool.arequest(170- method, url, headers=headers, stream=stream, ext=ext171- )259+ url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],260+ headers: typing.List[typing.Tuple[bytes, bytes]],261+ stream: typing.AsyncIterable[bytes],262+ extensions: dict,263+ ) -> typing.Tuple[264+ int, typing.List[typing.Tuple[bytes, bytes]], typing.AsyncIterable[bytes], dict265+ ]:266+ with map_httpcore_exceptions():267+ status_code, headers, byte_stream, extenstions = await self._pool.arequest(268+ method=method,269+ url=url,270+ headers=headers,271+ stream=httpcore.AsyncIteratorByteStream(stream.__aiter__()),272+ ext=extensions,273+ )274 275+ async def response_stream() -> typing.AsyncIterator[bytes]:276+ with map_httpcore_exceptions():277+ async for part in byte_stream:278+ yield part279+280+ async def aclose() -> None:281+ with map_httpcore_exceptions():282+ await byte_stream.aclose()283+284+ ensure_http_version_reason_phrase_as_bytes(extensions)285+ extensions["aclose"] = aclose286+287+ return status_code, headers, response_stream(), extensions288+289 async def aclose(self) -> None:290 await self._pool.aclose()modified:httpx/_transports/mock.py+22 added-19 removed
1 import asyncio2-from typing import Callable, List, Optional, Tuple2+import typing3 4-import httpcore5-4 from .._models import Request5+from .base import AsyncBaseTransport, BaseTransport6 7 9-class MockTransport(httpcore.SyncHTTPTransport, httpcore.AsyncHTTPTransport):10- def __init__(self, handler: Callable) -> None:8+class MockTransport(AsyncBaseTransport, BaseTransport):9+ def __init__(self, handler: typing.Callable) -> None:10 self.handler = handler11 13- def request(12+ def handle_request(13 self,14 method: bytes,16- url: Tuple[bytes, bytes, Optional[int], bytes],17- headers: List[Tuple[bytes, bytes]] = None,18- stream: httpcore.SyncByteStream = None,19- ext: dict = None,20- ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.SyncByteStream, dict]:15+ url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],16+ headers: typing.List[typing.Tuple[bytes, bytes]],17+ stream: typing.Iterable[bytes],18+ extensions: dict,19+ ) -> typing.Tuple[20+ int, typing.List[typing.Tuple[bytes, bytes]], typing.Iterable[bytes], dict21+ ]:22 request = Request(23 method=method,24 url=url,25 headers=headers,4 unmodified lines30 return (31 response.status_code,32 response.headers.raw,33 response.stream,33- response.ext,34+ response.extensions,35 )36 36- async def arequest(37+ async def handle_async_request(38 self,39 method: bytes,39- url: Tuple[bytes, bytes, Optional[int], bytes],40- headers: List[Tuple[bytes, bytes]] = None,41- stream: httpcore.AsyncByteStream = None,42- ext: dict = None,43- ) -> Tuple[int, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream, dict]:40+ url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],41+ headers: typing.List[typing.Tuple[bytes, bytes]],42+ stream: typing.AsyncIterable[bytes],43+ extensions: dict,44+ ) -> typing.Tuple[45+ int, typing.List[typing.Tuple[bytes, bytes]], typing.AsyncIterable[bytes], dict46+ ]:47 request = Request(48 method=method,49 url=url,50 headers=headers,14 unmodified lines65 return (66 response.status_code,67 response.headers.raw,68 response.stream,66- response.ext,69+ response.extensions,70 )modified:httpx/_transports/wsgi.py+11 added-13 removed
1 unmodified line2 import itertools3 import typing4 from urllib.parse import unquote5 6-import httpcore6+from .base import BaseTransport7 8 9 def _skip_leading_empty_chunks(body: typing.Iterable) -> typing.Iterable:10 body = iter(body)2 unmodified lines13 return itertools.chain([chunk], body)14 return []15 16 17-class WSGITransport(httpcore.SyncHTTPTransport):17+class WSGITransport(BaseTransport):18 """19 A custom transport that handles sending requests directly to an WSGI app.20 The simplest way to use this functionality is to use the `app` argument.21 36 unmodified lines58 self.raise_app_exceptions = raise_app_exceptions59 self.script_name = script_name60 self.remote_addr = remote_addr61 62- def request(62+ def handle_request(63 self,64 method: bytes,65 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],66- headers: typing.List[typing.Tuple[bytes, bytes]] = None,67- stream: httpcore.SyncByteStream = None,68- ext: dict = None,66+ headers: typing.List[typing.Tuple[bytes, bytes]],67+ stream: typing.Iterable[bytes],68+ extensions: dict,69 ) -> typing.Tuple[70- int, typing.List[typing.Tuple[bytes, bytes]], httpcore.SyncByteStream, dict70+ int, typing.List[typing.Tuple[bytes, bytes]], typing.Iterable[bytes], dict71 ]:72- headers = [] if headers is None else headers73- stream = httpcore.PlainByteStream(content=b"") if stream is None else stream72+ wsgi_input = io.BytesIO(b"".join(stream))73 74 scheme, host, port, full_path = url75 path, _, query = full_path.partition(b"?")76 if port is None:1 unmodified line78 79 environ = {80 "wsgi.version": (1, 0),81 "wsgi.url_scheme": scheme.decode("ascii"),83- "wsgi.input": io.BytesIO(b"".join(stream)),82+ "wsgi.input": wsgi_input,83 "wsgi.errors": io.BytesIO(),84 "wsgi.multithread": True,85 "wsgi.multiprocess": False,86 "wsgi.run_once": False,37 unmodified lines124 headers = [125 (key.encode("ascii"), value.encode("ascii"))126 for key, value in seen_response_headers127 ]129- stream = httpcore.IteratorByteStream(iterator=result)130- ext = {}128+ extensions = {}129 132- return (status_code, headers, stream, ext)130+ return (status_code, headers, result, extensions)modified:httpx/__init__.py+3 added
34 unmodified lines35 )36 from ._models import URL, Cookies, Headers, QueryParams, Request, Response37 from ._status_codes import StatusCode, codes38 from ._transports.asgi import ASGITransport39+from ._transports.base import AsyncBaseTransport, BaseTransport40 from ._transports.default import AsyncHTTPTransport, HTTPTransport41 from ._transports.mock import MockTransport42 from ._transports.wsgi import WSGITransport43 1 unmodified line45 "__description__",46 "__title__",47 "__version__",48 "ASGITransport",49+ "AsyncBaseTransport",50 "AsyncClient",51 "AsyncHTTPTransport",52 "Auth",53+ "BaseTransport",54 "BasicAuth",55 "Client",56 "CloseError",57 "codes",58 unmodified linesmodified:httpx/_client.py+97 added-91 removed
2 unmodified lines3 import typing4 import warnings5 from types import TracebackType6 7-import httpcore8-7 from .__version__ import __version__8 from ._auth import Auth, BasicAuth, FunctionAuth9 from ._config import (10 DEFAULT_LIMITS,6 unmodified lines17 UnsetType,18 )19 from ._decoders import SUPPORTED_DECODERS20 from ._exceptions import (23- HTTPCORE_EXC_MAP,21 InvalidURL,22 RemoteProtocolError,23 TooManyRedirects,27- map_exceptions,24+ request_context,25 )26 from ._models import URL, Cookies, Headers, QueryParams, Request, Response27 from ._status_codes import codes28 from ._transports.asgi import ASGITransport29+from ._transports.base import AsyncBaseTransport, BaseTransport30 from ._transports.default import AsyncHTTPTransport, HTTPTransport31 from ._transports.wsgi import WSGITransport32 from ._types import (33 AuthTypes,532 unmodified lines566 verify: VerifyTypes = True,567 cert: CertTypes = None,568 http2: bool = False,569 proxies: ProxiesTypes = None,572- mounts: typing.Mapping[str, httpcore.SyncHTTPTransport] = None,570+ mounts: typing.Mapping[str, BaseTransport] = None,571 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,572 limits: Limits = DEFAULT_LIMITS,573 pool_limits: Limits = None,574 max_redirects: int = DEFAULT_MAX_REDIRECTS,575 event_hooks: typing.Mapping[str, typing.List[typing.Callable]] = None,576 base_url: URLTypes = "",579- transport: httpcore.SyncHTTPTransport = None,577+ transport: BaseTransport = None,578 app: typing.Callable = None,579 trust_env: bool = True,580 ):581 super().__init__(35 unmodified lines617 transport=transport,618 app=app,619 trust_env=trust_env,620 )623- self._mounts: typing.Dict[624- URLPattern, typing.Optional[httpcore.SyncHTTPTransport]625- ] = {621+ self._mounts: typing.Dict[URLPattern, typing.Optional[BaseTransport]] = {622 URLPattern(key): None623 if proxy is None624 else self._init_proxy_transport(625 proxy,17 unmodified lines643 verify: VerifyTypes = True,644 cert: CertTypes = None,645 http2: bool = False,646 limits: Limits = DEFAULT_LIMITS,651- transport: httpcore.SyncHTTPTransport = None,647+ transport: BaseTransport = None,648 app: typing.Callable = None,649 trust_env: bool = True,654- ) -> httpcore.SyncHTTPTransport:650+ ) -> BaseTransport:651 if transport is not None:652 return transport653 654 if app is not None:10 unmodified lines665 cert: CertTypes = None,666 http2: bool = False,667 limits: Limits = DEFAULT_LIMITS,668 trust_env: bool = True,673- ) -> httpcore.SyncHTTPTransport:669+ ) -> BaseTransport:670 return HTTPTransport(671 verify=verify,672 cert=cert,673 http2=http2,1 unmodified line675 trust_env=trust_env,676 proxy=proxy,677 )678 683- def _transport_for_url(self, url: URL) -> httpcore.SyncHTTPTransport:679+ def _transport_for_url(self, url: URL) -> BaseTransport:680 """681 Returns the transport instance that should be used for a given URL.682 This will either be the standard connection pool, or a proxy.683 """86 unmodified lines770 timeout=timeout,771 allow_redirects=allow_redirects,772 history=[],773 )778-779- if not stream:780- try:774+ try:775+ if not stream:776 response.read()782- finally:783- response.close()777 785- try:778 for hook in self._event_hooks["response"]:779 hook(response)788- except Exception:789- response.close()790- raise780 792- return response781+ return response782 783+ except Exception as exc:784+ response.close()785+ raise exc786+787 def _send_handling_auth(788 self,789 request: Request,790 auth: Auth,14 unmodified lines805 allow_redirects=allow_redirects,806 history=history,807 )808 try:816- next_request = auth_flow.send(response)817- except StopIteration:818- return response819- except BaseException as exc:820- response.close()821- raise exc from None822- else:809+ try:810+ next_request = auth_flow.send(response)811+ except StopIteration:812+ return response813+814 response.history = list(history)815 response.read()816 request = next_request817 history.append(response)818 819+ except Exception as exc:820+ response.close()821+ raise exc822+823 def _send_handling_redirects(824 self,825 request: Request,826 timeout: Timeout,6 unmodified lines833 "Exceeded maximum allowed redirects.", request=request834 )835 836 response = self._send_single_request(request, timeout)837+ try:842- response.history = list(history)838+ response.history = list(history)839 844- if not response.is_redirect:845- return response840+ if not response.is_redirect:841+ return response842 847- if allow_redirects:848- response.read()849- request = self._build_redirect_request(request, response)850- history = history + [response]843+ request = self._build_redirect_request(request, response)844+ history = history + [response]845 852- if not allow_redirects:853- response.next_request = request854- return response846+ if allow_redirects:847+ response.read()848+ else:849+ response.next_request = request850+ return response851 852+ except Exception as exc:853+ response.close()854+ raise exc855+856 def _send_single_request(self, request: Request, timeout: Timeout) -> Response:857 """858 Sends a single request, without handling any redirections.859 """860 transport = self._transport_for_url(request.url)861 timer = Timer()862 timer.sync_start()863 864- with map_exceptions(HTTPCORE_EXC_MAP, request=request):865- (status_code, headers, stream, ext) = transport.request(864+ with request_context(request=request):865+ (status_code, headers, stream, extensions) = transport.handle_request(866 request.method.encode(),867 request.url.raw,868 headers=request.headers.raw,869 stream=request.stream, # type: ignore870- ext={"timeout": timeout.as_dict()},870+ extensions={"timeout": timeout.as_dict()},871 )872 873 def on_close(response: Response) -> None:874 response.elapsed = datetime.timedelta(seconds=timer.sync_elapsed())875- if hasattr(stream, "close"):876- stream.close()875+ if "close" in extensions:876+ extensions["close"]()877 878 response = Response(879 status_code,880 headers=headers,881- stream=stream, # type: ignore882- ext=ext,881+ stream=stream,882+ extensions=extensions,883 request=request,884 on_close=on_close,885 )886 314 unmodified lines1201 verify: VerifyTypes = True,1202 cert: CertTypes = None,1203 http2: bool = False,1204 proxies: ProxiesTypes = None,1205- mounts: typing.Mapping[str, httpcore.AsyncHTTPTransport] = None,1205+ mounts: typing.Mapping[str, AsyncBaseTransport] = None,1206 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,1207 limits: Limits = DEFAULT_LIMITS,1208 pool_limits: Limits = None,1209 max_redirects: int = DEFAULT_MAX_REDIRECTS,1210 event_hooks: typing.Mapping[str, typing.List[typing.Callable]] = None,1211 base_url: URLTypes = "",1212- transport: httpcore.AsyncHTTPTransport = None,1212+ transport: AsyncBaseTransport = None,1213 app: typing.Callable = None,1214 trust_env: bool = True,1215 ):1216 super().__init__(36 unmodified lines1253 app=app,1254 trust_env=trust_env,1255 )1256 1257- self._mounts: typing.Dict[1258- URLPattern, typing.Optional[httpcore.AsyncHTTPTransport]1259- ] = {1257+ self._mounts: typing.Dict[URLPattern, typing.Optional[AsyncBaseTransport]] = {1258 URLPattern(key): None1259 if proxy is None1260 else self._init_proxy_transport(1261 proxy,16 unmodified lines1278 verify: VerifyTypes = True,1279 cert: CertTypes = None,1280 http2: bool = False,1281 limits: Limits = DEFAULT_LIMITS,1284- transport: httpcore.AsyncHTTPTransport = None,1282+ transport: AsyncBaseTransport = None,1283 app: typing.Callable = None,1284 trust_env: bool = True,1287- ) -> httpcore.AsyncHTTPTransport:1285+ ) -> AsyncBaseTransport:1286 if transport is not None:1287 return transport1288 1289 if app is not None:10 unmodified lines1300 cert: CertTypes = None,1301 http2: bool = False,1302 limits: Limits = DEFAULT_LIMITS,1303 trust_env: bool = True,1306- ) -> httpcore.AsyncHTTPTransport:1304+ ) -> AsyncBaseTransport:1305 return AsyncHTTPTransport(1306 verify=verify,1307 cert=cert,1308 http2=http2,1 unmodified line1310 trust_env=trust_env,1311 proxy=proxy,1312 )1313 1316- def _transport_for_url(self, url: URL) -> httpcore.AsyncHTTPTransport:1314+ def _transport_for_url(self, url: URL) -> AsyncBaseTransport:1315 """1316 Returns the transport instance that should be used for a given URL.1317 This will either be the standard connection pool, or a proxy.1318 """87 unmodified lines1406 timeout=timeout,1407 allow_redirects=allow_redirects,1408 history=[],1409 )1412-1413- if not stream:1414- try:1410+ try:1411+ if not stream:1412 await response.aread()1416- finally:1417- await response.aclose()1413 1419- try:1414 for hook in self._event_hooks["response"]:1415 await hook(response)1422- except Exception:1423- await response.aclose()1424- raise1416 1426- return response1417+ return response1418 1419+ except Exception as exc:1420+ await response.aclose()1421+ raise exc1422+1423 async def _send_handling_auth(1424 self,1425 request: Request,1426 auth: Auth,14 unmodified lines1441 allow_redirects=allow_redirects,1442 history=history,1443 )1444 try:1450- next_request = await auth_flow.asend(response)1451- except StopAsyncIteration:1452- return response1453- except BaseException as exc:1454- await response.aclose()1455- raise exc from None1456- else:1445+ try:1446+ next_request = await auth_flow.asend(response)1447+ except StopAsyncIteration:1448+ return response1449+1450 response.history = list(history)1451 await response.aread()1452 request = next_request1453 history.append(response)1454 1455+ except Exception as exc:1456+ await response.aclose()1457+ raise exc1458+1459 async def _send_handling_redirects(1460 self,1461 request: Request,1462 timeout: Timeout,6 unmodified lines1469 "Exceeded maximum allowed redirects.", request=request1470 )1471 1472 response = await self._send_single_request(request, timeout)1473+ try:1476- response.history = list(history)1474+ response.history = list(history)1475 1478- if not response.is_redirect:1479- return response1476+ if not response.is_redirect:1477+ return response1478 1481- if allow_redirects:1482- await response.aread()1483- request = self._build_redirect_request(request, response)1484- history = history + [response]1479+ request = self._build_redirect_request(request, response)1480+ history = history + [response]1481 1486- if not allow_redirects:1487- response.next_request = request1488- return response1482+ if allow_redirects:1483+ await response.aread()1484+ else:1485+ response.next_request = request1486+ return response1487 1488+ except Exception as exc:1489+ await response.aclose()1490+ raise exc1491+1492 async def _send_single_request(1493 self, request: Request, timeout: Timeout1494 ) -> Response:1495 """2 unmodified lines1498 transport = self._transport_for_url(request.url)1499 timer = Timer()1500 await timer.async_start()1501 1500- with map_exceptions(HTTPCORE_EXC_MAP, request=request):1501- (status_code, headers, stream, ext) = await transport.arequest(1502+ with request_context(request=request):1503+ (1504+ status_code,1505+ headers,1506+ stream,1507+ extensions,1508+ ) = await transport.handle_async_request(1509 request.method.encode(),1510 request.url.raw,1511 headers=request.headers.raw,1512 stream=request.stream, # type: ignore1506- ext={"timeout": timeout.as_dict()},1513+ extensions={"timeout": timeout.as_dict()},1514 )1515 1516 async def on_close(response: Response) -> None:1517 response.elapsed = datetime.timedelta(seconds=await timer.async_elapsed())1511- if hasattr(stream, "aclose"):1512- with map_exceptions(HTTPCORE_EXC_MAP, request=request):1513- await stream.aclose()1518+ if "aclose" in extensions:1519+ await extensions["aclose"]()1520 1521 response = Response(1522 status_code,1523 headers=headers,1518- stream=stream, # type: ignore1519- ext=ext,1524+ stream=stream,1525+ extensions=extensions,1526 request=request,1527 on_close=on_close,1528 )1529 323 unmodified linesmodified:httpx/_decoders.py+8 added-6 removed
6 unmodified lines7 import io8 import typing9 import zlib10 11+from ._exceptions import DecodingError12+13 try:14 import brotli15 except ImportError: # pragma: nocover16 brotli = None38 unmodified lines55 except zlib.error as exc:56 if was_first_attempt:57 self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)58 return self.decode(data)57- raise ValueError(str(exc))59+ raise DecodingError(str(exc)) from exc60 61 def flush(self) -> bytes:62 try:63 return self.decompressor.flush()64 except zlib.error as exc: # pragma: nocover63- raise ValueError(str(exc))65+ raise DecodingError(str(exc)) from exc66 67 68 class GZipDecoder(ContentDecoder):69 """8 unmodified lines78 def decode(self, data: bytes) -> bytes:79 try:80 return self.decompressor.decompress(data)81 except zlib.error as exc:80- raise ValueError(str(exc))82+ raise DecodingError(str(exc)) from exc83 84 def flush(self) -> bytes:85 try:86 return self.decompressor.flush()87 except zlib.error as exc: # pragma: nocover86- raise ValueError(str(exc))88+ raise DecodingError(str(exc)) from exc89 90 91 class BrotliDecoder(ContentDecoder):92 """26 unmodified lines119 self.seen_data = True120 try:121 return self._decompress(data)122 except brotli.error as exc:121- raise ValueError(str(exc))123+ raise DecodingError(str(exc)) from exc124 125 def flush(self) -> bytes:126 if not self.seen_data:127 return b""1 unmodified line129 if hasattr(self.decompressor, "finish"):130 self.decompressor.finish()131 return b""132 except brotli.error as exc: # pragma: nocover131- raise ValueError(str(exc))133+ raise DecodingError(str(exc)) from exc134 135 136 class MultiDecoder(ContentDecoder):137 """232 unmodified linesmodified:httpx/_exceptions.py+31 added-49 removed
32 unmodified lines33 """34 import contextlib35 import typing36 37-import httpcore38-37 if typing.TYPE_CHECKING:38 from ._models import Request, Response # pragma: nocover39 40 14 unmodified lines55 print(f"HTTP Exception for {exc.request.url} - {exc}")56 ```57 """58 61- def __init__(self, message: str, *, request: "Request") -> None:59+ def __init__(self, message: str) -> None:60 super().__init__(message)63- self.request = request61 62 63 class RequestError(HTTPError):64 """65 Base class for all exceptions that may occur when issuing a `.request()`.66 """67 71- def __init__(self, message: str, *, request: "Request") -> None:72- super().__init__(message, request=request)68+ def __init__(self, message: str, *, request: "Request" = None) -> None:69+ super().__init__(message)70+ # At the point an exception is raised we won't typically have a request71+ # instance to associate it with.72+ #73+ # The 'request_context' context manager is used within the Client and74+ # Response methods in order to ensure that any raised exceptions75+ # have a `.request` property set on them.76+ self._request = request77 78+ @property79+ def request(self) -> "Request":80+ if self._request is None:81+ raise RuntimeError("The .request property has not been set.")82+ return self._request83 84+ @request.setter85+ def request(self, request: "Request") -> None:86+ self._request = request87+88+89 class TransportError(RequestError):90 """91 Base class for all exceptions that occur at the level of the Transport API.78-79- All of these exceptions also have an equivelent mapping in `httpcore`.92 """93 94 95 # Timeout exceptions...134 unmodified lines230 231 def __init__(232 self, message: str, *, request: "Request", response: "Response"233 ) -> None:222- super().__init__(message, request=request)234+ super().__init__(message)235+ self.request = request236 self.response = response237 238 239 class InvalidURL(Exception):90 unmodified lines330 super().__init__(message)331 332 333 @contextlib.contextmanager321-def map_exceptions(322- mapping: typing.Mapping[typing.Type[Exception], typing.Type[Exception]],323- **kwargs: typing.Any,324-) -> typing.Iterator[None]:334+def request_context(request: "Request" = None) -> typing.Iterator[None]:335+ """336+ A context manager that can be used to attach the given request context337+ to any `RequestError` exceptions that are raised within the block.338+ """339 try:340 yield327- except Exception as exc:328- mapped_exc = None329-330- for from_exc, to_exc in mapping.items():331- if not isinstance(exc, from_exc):332- continue333- # We want to map to the most specific exception we can find.334- # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to335- # `httpx.ReadTimeout`, not just `httpx.TimeoutException`.336- if mapped_exc is None or issubclass(to_exc, mapped_exc):337- mapped_exc = to_exc338-339- if mapped_exc is None:340- raise341-342- message = str(exc)343- raise mapped_exc(message, **kwargs) from exc # type: ignore344-345-346-HTTPCORE_EXC_MAP = {347- httpcore.TimeoutException: TimeoutException,348- httpcore.ConnectTimeout: ConnectTimeout,349- httpcore.ReadTimeout: ReadTimeout,350- httpcore.WriteTimeout: WriteTimeout,351- httpcore.PoolTimeout: PoolTimeout,352- httpcore.NetworkError: NetworkError,353- httpcore.ConnectError: ConnectError,354- httpcore.ReadError: ReadError,355- httpcore.WriteError: WriteError,356- httpcore.CloseError: CloseError,357- httpcore.ProxyError: ProxyError,358- httpcore.UnsupportedProtocol: UnsupportedProtocol,359- httpcore.ProtocolError: ProtocolError,360- httpcore.LocalProtocolError: LocalProtocolError,361- httpcore.RemoteProtocolError: RemoteProtocolError,362-}341+ except RequestError as exc:342+ if request is not None:343+ exc.request = request344+ raise excmodified:httpx/_models.py+23 added-29 removed
1 import cgi2-import contextlib2 import datetime3 import email.message4 import json as jsonlib5 import typing16 unmodified lines22 TextChunker,23 TextDecoder,24 )25 from ._exceptions import (27- HTTPCORE_EXC_MAP,26 CookieConflict,29- DecodingError,27 HTTPStatusError,28 InvalidURL,29 RequestNotRead,30 ResponseClosed,31 ResponseNotRead,32 StreamConsumed,36- map_exceptions,33+ request_context,34 )35 from ._status_codes import codes36 from ._types import (37 ByteStream,867 unmodified lines905 html: str = None,906 json: typing.Any = None,907 stream: ByteStream = None,908 request: Request = None,912- ext: dict = None,909+ extensions: dict = None,910 history: typing.List["Response"] = None,911 on_close: typing.Callable = None,912 ):913 self.status_code = status_code6 unmodified lines920 self.next_request: typing.Optional[Request] = None921 922 self.call_next: typing.Optional[typing.Callable] = None923 927- self.ext = {} if ext is None else ext924+ self.extensions = {} if extensions is None else extensions925 self.history = [] if history is None else list(history)926 self._on_close = on_close927 928 self.is_closed = False62 unmodified lines991 self._request = value992 993 @property994 def http_version(self) -> str:998- return self.ext.get("http_version", "HTTP/1.1")995+ try:996+ return self.extensions["http_version"].decode("ascii", errors="ignore")997+ except KeyError:998+ return "HTTP/1.1"999 1000 @property1001 def reason_phrase(self) -> str:1002- return self.ext.get("reason", codes.get_reason_phrase(self.status_code))1002+ try:1003+ return self.extensions["reason_phrase"].decode("ascii", errors="ignore")1004+ except KeyError:1005+ return codes.get_reason_phrase(self.status_code)1006 1007 @property1008 def url(self) -> typing.Optional[URL]:1009 """144 unmodified lines1154 1155 def __repr__(self) -> str:1156 return f"<Response [{self.status_code} {self.reason_phrase}]>"1157 1155- @contextlib.contextmanager1156- def _wrap_decoder_errors(self) -> typing.Iterator[None]:1157- # If the response has an associated request instance, we want decoding1158- # errors to be raised as proper `httpx.DecodingError` exceptions.1159- try:1160- yield1161- except ValueError as exc:1162- if self._request is None:1163- raise exc1164- raise DecodingError(message=str(exc), request=self.request) from exc1165-1158 def read(self) -> bytes:1159 """1160 Read and return the response content.1161 """12 unmodified lines1174 yield self._content[i : i + chunk_size]1175 else:1176 decoder = self._get_content_decoder()1177 chunker = ByteChunker(chunk_size=chunk_size)1186- with self._wrap_decoder_errors():1178+ with request_context(request=self._request):1179 for raw_bytes in self.iter_raw():1180 decoded = decoder.decode(raw_bytes)1181 for chunk in chunker.decode(decoded):1182 yield chunk10 unmodified lines1193 string encoding.1194 """1195 decoder = TextDecoder(encoding=self.encoding)1196 chunker = TextChunker(chunk_size=chunk_size)1205- with self._wrap_decoder_errors():1197+ with request_context(request=self._request):1198 for byte_content in self.iter_bytes():1199 text_content = decoder.decode(byte_content)1200 for chunk in chunker.decode(text_content):1201 yield chunk4 unmodified lines1206 yield chunk1207 1208 def iter_lines(self) -> typing.Iterator[str]:1209 decoder = LineDecoder()1218- with self._wrap_decoder_errors():1210+ with request_context(request=self._request):1211 for text in self.iter_text():1212 for line in decoder.decode(text):1213 yield line1214 for line in decoder.flush():13 unmodified lines1228 self.is_stream_consumed = True1229 self._num_bytes_downloaded = 01230 chunker = ByteChunker(chunk_size=chunk_size)1231 1240- with map_exceptions(HTTPCORE_EXC_MAP, request=self._request):1232+ with request_context(request=self._request):1233 for raw_stream_bytes in self.stream:1234 self._num_bytes_downloaded += len(raw_stream_bytes)1235 for chunk in chunker.decode(raw_stream_bytes):1236 yield chunk10 unmodified lines1247 """1248 if not self.is_closed:1249 self.is_closed = True1250 if self._on_close is not None:1251+ with request_context(request=self._request):1259- self._on_close(self)1252+ self._on_close(self)1253 1254 async def aread(self) -> bytes:1255 """1256 Read and return the response content.13 unmodified lines1270 yield self._content[i : i + chunk_size]1271 else:1272 decoder = self._get_content_decoder()1273 chunker = ByteChunker(chunk_size=chunk_size)1281- with self._wrap_decoder_errors():1274+ with request_context(request=self._request):1275 async for raw_bytes in self.aiter_raw():1276 decoded = decoder.decode(raw_bytes)1277 for chunk in chunker.decode(decoded):1278 yield chunk10 unmodified lines1289 string encoding.1290 """1291 decoder = TextDecoder(encoding=self.encoding)1292 chunker = TextChunker(chunk_size=chunk_size)1300- with self._wrap_decoder_errors():1293+ with request_context(request=self._request):1294 async for byte_content in self.aiter_bytes():1295 text_content = decoder.decode(byte_content)1296 for chunk in chunker.decode(text_content):1297 yield chunk4 unmodified lines1302 yield chunk1303 1304 async def aiter_lines(self) -> typing.AsyncIterator[str]:1305 decoder = LineDecoder()1313- with self._wrap_decoder_errors():1306+ with request_context(request=self._request):1307 async for text in self.aiter_text():1308 for line in decoder.decode(text):1309 yield line1310 for line in decoder.flush():13 unmodified lines1324 self.is_stream_consumed = True1325 self._num_bytes_downloaded = 01326 chunker = ByteChunker(chunk_size=chunk_size)1327 1335- with map_exceptions(HTTPCORE_EXC_MAP, request=self._request):1328+ with request_context(request=self._request):1329 async for raw_stream_bytes in self.stream:1330 self._num_bytes_downloaded += len(raw_stream_bytes)1331 for chunk in chunker.decode(raw_stream_bytes):1332 yield chunk10 unmodified lines1343 """1344 if not self.is_closed:1345 self.is_closed = True1346 if self._on_close is not None:1347+ with request_context(request=self._request):1354- await self._on_close(self)1348+ await self._on_close(self)1349 1350 1351 class Cookies(MutableMapping):1352 """187 unmodified linesmodified:tests/client/test_async_client.py+4 added-24 removed
1 import typing2 from datetime import timedelta3 4-import httpcore4 import pytest5 6 import httpx7 159 unmodified lines167 168 169 @pytest.mark.usefixtures("async_environment")170 async def test_context_managed_transport():172- class Transport(httpcore.AsyncHTTPTransport):171+ class Transport(httpx.AsyncBaseTransport):172 def __init__(self):173 self.events = []174 175 async def aclose(self):177- # The base implementation of httpcore.AsyncHTTPTransport just176+ # The base implementation of httpx.AsyncBaseTransport just177 # calls into `.aclose`, so simple transport cases can just override178 # this method for any cleanup, where more complex cases179 # might want to additionally override `__aenter__`/`__aexit__`.180 self.events.append("transport.aclose")18 unmodified lines199 200 201 @pytest.mark.usefixtures("async_environment")202 async def test_context_managed_transport_and_mount():204- class Transport(httpcore.AsyncHTTPTransport):203+ class Transport(httpx.AsyncBaseTransport):204 def __init__(self, name: str):205 self.name: str = name206 self.events: typing.List[str] = []207 208 async def aclose(self):210- # The base implementation of httpcore.AsyncHTTPTransport just209+ # The base implementation of httpx.AsyncBaseTransport just210 # calls into `.aclose`, so simple transport cases can just override211 # this method for any cleanup, where more complex cases212 # might want to additionally override `__aenter__`/`__aexit__`.213 self.events.append(f"{self.name}.aclose")88 unmodified lines302 assert response.json() == {"app": "mounted"}303 304 305 @pytest.mark.usefixtures("async_environment")307-async def test_response_aclose_map_exceptions():308- class BrokenStream:309- async def __aiter__(self):310- # so we're an AsyncIterator311- pass # pragma: nocover312-313- async def aclose(self):314- raise httpcore.CloseError(OSError(104, "Connection reset by peer"))315-316- def handle(request: httpx.Request) -> httpx.Response:317- return httpx.Response(200, stream=BrokenStream())318-319- async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client:320- async with client.stream("GET", "http://example.com") as response:321- with pytest.raises(httpx.CloseError):322- await response.aclose()323-324-325-@pytest.mark.usefixtures("async_environment")306 async def test_async_mock_transport():307 async def hello_world(request):308 return httpx.Response(200, text="Hello, world!")309 6 unmodified linesmodified:tests/client/test_client.py+4 added-5 removed
1 import typing2 from datetime import timedelta3 4-import httpcore4 import pytest5 6 import httpx7 214 unmodified lines222 httpx.AsyncClient(pool_limits=limits)223 224 225 def test_context_managed_transport():227- class Transport(httpcore.SyncHTTPTransport):226+ class Transport(httpx.BaseTransport):227 def __init__(self):228 self.events = []229 230 def close(self):232- # The base implementation of httpcore.SyncHTTPTransport just231+ # The base implementation of httpx.BaseTransport just232 # calls into `.close`, so simple transport cases can just override233 # this method for any cleanup, where more complex cases234 # might want to additionally override `__enter__`/`__exit__`.235 self.events.append("transport.close")17 unmodified lines253 ]254 255 256 def test_context_managed_transport_and_mount():258- class Transport(httpcore.SyncHTTPTransport):257+ class Transport(httpx.BaseTransport):258 def __init__(self, name: str):259 self.name: str = name260 self.events: typing.List[str] = []261 262 def close(self):264- # The base implementation of httpcore.SyncHTTPTransport just263+ # The base implementation of httpx.BaseTransport just264 # calls into `.close`, so simple transport cases can just override265 # this method for any cleanup, where more complex cases266 # might want to additionally override `__enter__`/`__exit__`.267 self.events.append(f"{self.name}.close")118 unmodified linesmodified:tests/client/test_redirects.py+8 added-4 removed
1-import httpcore1 import pytest2 3 import httpx4 5 6 def redirects(request: httpx.Request) -> httpx.Response:7 if request.url.scheme not in ("http", "https"):9- raise httpcore.UnsupportedProtocol(10- f"Scheme {request.url.scheme!r} not supported."11- )8+ raise httpx.UnsupportedProtocol(f"Scheme {request.url.scheme!r} not supported.")9 10 if request.url.path == "/redirect_301":11 status_code = httpx.codes.MOVED_PERMANENTLY12 content = b"<a href='https://example.org/'>here</a>"379 unmodified lines392 client = httpx.Client(transport=httpx.MockTransport(redirects))393 with pytest.raises(httpx.UnsupportedProtocol) as e:394 client.post("https://example.org/redirect_custom_scheme")395 assert str(e.value) == "Scheme 'market' not supported."396+397+398+@pytest.mark.usefixtures("async_environment")399+async def test_async_invalid_redirect():400+ async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:401+ with pytest.raises(httpx.RemoteProtocolError):402+ await client.get("http://example.org/invalid_redirect")modified:tests/models/test_responses.py+3 added-3 removed
731 unmodified lines732 headers = {"Content-Type": "application/json"}733 # force incorrect guess from `guess_json_utf` to trigger error734 with mock.patch("httpx._models.guess_json_utf", return_value="utf-32"):735 response = httpx.Response(200, content=content, headers=headers)736- with pytest.raises(ValueError):736+ with pytest.raises(json.decoder.JSONDecodeError):737 response.json()738 739 740 @pytest.mark.parametrize(25 unmodified lines766 def test_decode_error_with_request(header_value):767 headers = [(b"Content-Encoding", header_value)]768 body = b"test 123"769 compressed_body = brotli.compress(body)[3:]770- with pytest.raises(ValueError):770+ with pytest.raises(httpx.DecodingError):771 httpx.Response(772 200,773 headers=headers,774 content=compressed_body,12 unmodified lines787 def test_value_error_without_request(header_value):788 headers = [(b"Content-Encoding", header_value)]789 body = b"test 123"790 compressed_body = brotli.compress(body)[3:]791- with pytest.raises(ValueError):791+ with pytest.raises(httpx.DecodingError):792 httpx.Response(200, headers=headers, content=compressed_body)793 794 795 def test_response_with_unset_request():39 unmodified linesmodified:tests/conftest.py-15 removed
74 unmodified lines75 async def app(scope, receive, send):76 assert scope["type"] == "http"77 if scope["path"].startswith("/slow_response"):78 await slow_response(scope, receive, send)79- elif scope["path"].startswith("/slow_stream_response"):80- await slow_stream_response(scope, receive, send)79 elif scope["path"].startswith("/status"):80 await status_code(scope, receive, send)81 elif scope["path"].startswith("/echo_body"):82 await echo_body(scope, receive, send)27 unmodified lines110 )111 await send({"type": "http.response.body", "body": b"Hello, world!"})112 113 116-async def slow_stream_response(scope, receive, send):117- await send(118- {119- "type": "http.response.start",120- "status": 200,121- "headers": [[b"content-type", b"text/plain"]],122- }123- )124-125- await sleep(1)126- await send({"type": "http.response.body", "body": b"", "more_body": False})127-128-114 async def status_code(scope, receive, send):115 status_code = int(scope["path"].replace("/status/", ""))116 await send(117 {175 unmodified linesmodified:tests/test_asgi.py+36 added
68 unmodified lines69 await send({"type": "http.response.body", "body": output})70 raise RuntimeError()71 72 73+async def empty_stream():74+ yield b""75+76+77 @pytest.mark.usefixtures("async_environment")78+async def test_asgi_transport():79+ async with httpx.ASGITransport(app=hello_world) as transport:80+ status_code, headers, stream, ext = await transport.handle_async_request(81+ method=b"GET",82+ url=(b"http", b"www.example.org", 80, b"/"),83+ headers=[(b"Host", b"www.example.org")],84+ stream=empty_stream(),85+ extensions={},86+ )87+ body = b"".join([part async for part in stream])88+89+ assert status_code == 20090+ assert body == b"Hello, World!"91+92+93+@pytest.mark.usefixtures("async_environment")94+async def test_asgi_transport_no_body():95+ async with httpx.ASGITransport(app=echo_body) as transport:96+ status_code, headers, stream, ext = await transport.handle_async_request(97+ method=b"GET",98+ url=(b"http", b"www.example.org", 80, b"/"),99+ headers=[(b"Host", b"www.example.org")],100+ stream=empty_stream(),101+ extensions={},102+ )103+ body = b"".join([part async for part in stream])104+105+ assert status_code == 200106+ assert body == b""107+108+109+@pytest.mark.usefixtures("async_environment")110 async def test_asgi():111 async with httpx.AsyncClient(app=hello_world) as client:112 response = await client.get("http://www.example.org/")113 96 unmodified linesmodified:tests/test_decoders.py+1 added-1 removed
168 unmodified lines169 with pytest.raises(httpx.DecodingError):170 request = httpx.Request("GET", "https://example.org")171 httpx.Response(200, headers=headers, content=compressed_body, request=request)172 173- with pytest.raises(ValueError):173+ with pytest.raises(httpx.DecodingError):174 httpx.Response(200, headers=headers, content=compressed_body)175 176 177 @pytest.mark.parametrize(181 unmodified linesmodified:tests/test_exceptions.py+45 added-18 removed
1-from typing import Any1+from unittest import mock2 3 import httpcore4 import pytest5 6 import httpx7-from httpx._exceptions import HTTPCORE_EXC_MAP7+from httpx._transports.default import HTTPCORE_EXC_MAP8 9 10 def test_httpcore_all_exceptions_mapped() -> None:11 """16 unmodified lines28 """29 HTTPCore exception mapping works as expected.30 """31 32- # Make sure we don't just map to `NetworkError`.33- with pytest.raises(httpx.ConnectError):34- httpx.get("http://doesnotexist")32+ def connect_failed(*args, **kwargs):33+ raise httpcore.ConnectError()34 36- # Make sure streaming methods also map exceptions.37- url = server.url.copy_with(path="/slow_stream_response")38- timeout = httpx.Timeout(None, read=0.1)39- with httpx.stream("GET", url, timeout=timeout) as stream:40- with pytest.raises(httpx.ReadTimeout):41- stream.read()35+ class TimeoutStream:36+ def __iter__(self):37+ raise httpcore.ReadTimeout()38 43- # Make sure it also works with custom transports.44- class MockTransport(httpcore.SyncHTTPTransport):45- def request(self, *args: Any, **kwargs: Any) -> Any:46- raise httpcore.ProtocolError()39+ def close(self):40+ pass41 48- client = httpx.Client(transport=MockTransport())49- with pytest.raises(httpx.ProtocolError):50- client.get("http://testserver")42+ class CloseFailedStream:43+ def __iter__(self):44+ yield b""45 46+ def close(self):47+ raise httpcore.CloseError()48 49+ with mock.patch("httpcore.SyncConnectionPool.request", side_effect=connect_failed):50+ with pytest.raises(httpx.ConnectError):51+ httpx.get(server.url)52+53+ with mock.patch(54+ "httpcore.SyncConnectionPool.request",55+ return_value=(200, [], TimeoutStream(), {}),56+ ):57+ with pytest.raises(httpx.ReadTimeout):58+ httpx.get(server.url)59+60+ with mock.patch(61+ "httpcore.SyncConnectionPool.request",62+ return_value=(200, [], CloseFailedStream(), {}),63+ ):64+ with pytest.raises(httpx.CloseError):65+ httpx.get(server.url)66+67+68 def test_httpx_exceptions_exposed() -> None:69 """70 All exception classes defined in `httpx._exceptions`71 are exposed as public API.8 unmodified lines80 ]81 82 if not_exposed: # pragma: nocover83 pytest.fail(f"Unexposed HTTPX exceptions: {not_exposed}")84+85+86+def test_request_attribute() -> None:87+ # Exception without request attribute88+ exc = httpx.ReadTimeout("Read operation timed out")89+ with pytest.raises(RuntimeError):90+ exc.request91+92+ # Exception with request attribute93+ request = httpx.Request("GET", "https://www.example.com")94+ exc = httpx.ReadTimeout("Read operation timed out", request=request)95+ assert exc.request == requestmodified:CHANGELOG.md+19 added-2 removed
2 unmodified lines3 All notable changes to this project will be documented in this file.4 5 The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).6 7-## 0.17.17+## Master8 9+The 0.18.x release series formalises our low-level Transport API, introducing the10+base classes `httpx.BaseTransport` and `httpx.AsyncBaseTransport`.11+12+See the "Writing custom transports" documentation and the `httpx.BaseTransport.handle_request()`13+docstring for more complete details on implementing custom transports.14+15+Pull request #1522 includes a checklist of differences from the previous `httpcore` transport API,16+for developers implementing custom transports.17+18+### Changed19+20+* Transport instances now inherit from `httpx.BaseTransport` or `httpx.AsyncBaseTransport`,21+ and should implement either the `handle_request` method or `handle_async_request` method.22+* The `response.ext` property and `Response(ext=...)` argument are now named `extensions`.23+24+## 0.17.1 (March 15th, 2021)25+26 ### Fixed27 28 * Type annotation on `CertTypes` allows `keyfile` and `password` to be optional. (Pull #1503)29 * Fix httpcore pinned version. (Pull #1495)30 14-## 0.17.031+## 0.17.0 (February 28th, 2021)32 33 ### Added34 35 * Add `httpx.MockTransport()`, allowing to mock out a transport using pre-determined responses. (Pull #1401, Pull #1449)712 unmodified lines