Skip to content
Myr

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>

authored by Tom Christie · committed by GitHub · parent 6cb1672 · Browse files · 20 files+625 added−335 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

20 files+625 added−335 removed

  • tests:+101 added−70 removed
  • other:+524 added−265 removed

20 files+625 added−335 removed

modified:docs/advanced.md+24 added-17 removed
1013 unmodified lines
1014```10151016### Writing custom transports10171018A transport instance must implement the Transport API defined by1019[`httpcore`](https://www.encode.io/httpcore/api/). You1020should either subclass `httpcore.AsyncHTTPTransport` to implement a transport to1021use with `AsyncClient`, or subclass `httpcore.SyncHTTPTransport` to implement a1022transport to use with `Client`.1018A transport instance must implement the low-level Transport API, which deals1019with sending a single request, and returning a response. You should either1020subclass `httpx.BaseTransport` to implement a transport to use with `Client`,1021or subclass `httpx.AsyncBaseTransport` to implement a transport to1022use with `AsyncClient`.10231024At the layer of the transport API we're using plain primitives.1025No `Request` or `Response` models, no fancy `URL` or `Header` handling.1026This strict point of cut-off provides a clear design separation between the1027HTTPX API, and the low-level network handling.10281029See the `handle_request` and `handle_async_request` docstrings for more details1030on the specifics of the Transport API.10311032A complete example of a custom transport implementation would be:10331034```python1035import json1028import httpcore1036import httpx103710381031class HelloWorldTransport(httpcore.SyncHTTPTransport):1039class HelloWorldTransport(httpx.BaseTransport):1040 """1041 A mock transport that always returns a JSON "Hello, world!" response.1042 """10431036 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```10521053Which we can use in the same way:1054
36 unmodified lines
1091which transport an outgoing request should be routed via, with [the same style1092used for specifying proxy routing](#routing).10931094```python1087import httpcore1095import httpx10961090class HTTPSRedirectTransport(httpcore.SyncHTTPTransport):1097class HTTPSRedirectTransport(httpx.BaseTransport):1098 """1099 A transport that always redirects to HTTPS.1100 """11011095 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, extensions111211131114# A client where any `http` requests are always redirected to `https`1115mounts = {'http://': HTTPSRedirectTransport()}
34 unmodified lines
modified:httpx/_transports/asgi.py+21 added-19 removed
1from typing import TYPE_CHECKING, Callable, List, Optional, Tuple, Union1import typing2from urllib.parse import unquote34import httpcore4import sniffio56from .base import AsyncBaseTransport77if TYPE_CHECKING: # pragma: no cover8if typing.TYPE_CHECKING: # pragma: no cover9 import asyncio1011 import trio1212 Event = Union[asyncio.Event, trio.Event]13 Event = typing.Union[asyncio.Event, trio.Event]141516def create_event() -> "Event":17 if sniffio.current_async_library() == "trio":
5 unmodified lines
2324 return asyncio.Event()252626class ASGITransport(httpcore.AsyncHTTPTransport):27class 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 lines
58 """5960 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 = client7171 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 stream8175 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 lines
154 assert response_complete.is_set()155 assert status_code is not None156 assert response_headers is not None157158 stream = httpcore.PlainByteStream(content=b"".join(body_parts))159 ext = {}158 async def response_stream() -> typing.AsyncIterator[bytes]:159 yield b"".join(body_parts)160161 extensions = {}162161 return (status_code, response_headers, stream, ext)163 return (status_code, response_headers, response_stream(), extensions)
added:httpx/_transports/base.py+129 added
1import typing2from types import TracebackType34T = typing.TypeVar("T", bound="BaseTransport")5A = typing.TypeVar("A", bound="AsyncBaseTransport")678class BaseTransport:9 def __enter__(self: T) -> T:10 return self1112 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()1920 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.3233 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.3738 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.4142 Example usage:4344 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)5859 Arguments:6061 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'.7374 Returns a tuple of:7576 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: nocover9798 def close(self) -> None:99 pass100101102class AsyncBaseTransport:103 async def __aenter__(self: A) -> A:104 return self105106 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()113114 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: nocover127128 async def aclose(self) -> None:129 pass
modified:httpx/_transports/default.py+136 added-20 removed
22 unmodified lines
23# Using advanced httpcore configuration, with unix domain sockets.24transport = httpx.HTTPTransport(uds="socket.uds")25client = httpx.Client(transport=transport)26"""27import contextlib28import typing29from types import TracebackType3031import httpcore3233from .._config import DEFAULT_LIMITS, Limits, Proxy, create_ssl_context34from .._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)51from .._types import CertTypes, VerifyTypes52from .base import AsyncBaseTransport, BaseTransport5354T = typing.TypeVar("T", bound="HTTPTransport")55A = typing.TypeVar("A", bound="AsyncHTTPTransport")37Headers = typing.List[typing.Tuple[bytes, bytes]]38URL = typing.Tuple[bytes, bytes, typing.Optional[int], bytes]565758@contextlib.contextmanager59def map_httpcore_exceptions() -> typing.Iterator[None]:60 try:61 yield62 except Exception as exc:63 mapped_exc = None6465 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_exc7374 if mapped_exc is None: # pragma: nocover75 raise7677 message = str(exc)78 raise mapped_exc(message) from exc798081def 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")929394HTTPCORE_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}11111241class HTTPTransport(httpcore.SyncHTTPTransport):113class HTTPTransport(BaseTransport):114 def __init__(115 self,116 verify: VerifyTypes = True,117 cert: CertTypes = None,
44 unmodified lines
162 traceback: TracebackType = None,163 ) -> None:164 self._pool.__exit__(exc_type, exc_value, traceback)16594 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 )184185 def response_stream() -> typing.Iterator[bytes]:186 with map_httpcore_exceptions():187 for part in byte_stream:188 yield part189190 def close() -> None:191 with map_httpcore_exceptions():192 byte_stream.close()193194 ensure_http_version_reason_phrase_as_bytes(extensions)195 extensions["close"] = close196197 return status_code, headers, response_stream(), extensions198199 def close(self) -> None:200 self._pool.close()201202108class AsyncHTTPTransport(httpcore.AsyncHTTPTransport):203class AsyncHTTPTransport(AsyncBaseTransport):204 def __init__(205 self,206 verify: VerifyTypes = True,207 cert: CertTypes = None,
44 unmodified lines
252 traceback: TracebackType = None,253 ) -> None:254 await self._pool.__aexit__(exc_type, exc_value, traceback)255161 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 )274275 async def response_stream() -> typing.AsyncIterator[bytes]:276 with map_httpcore_exceptions():277 async for part in byte_stream:278 yield part279280 async def aclose() -> None:281 with map_httpcore_exceptions():282 await byte_stream.aclose()283284 ensure_http_version_reason_phrase_as_bytes(extensions)285 extensions["aclose"] = aclose286287 return status_code, headers, response_stream(), extensions288289 async def aclose(self) -> None:290 await self._pool.aclose()
modified:httpx/_transports/mock.py+22 added-19 removed
1import asyncio2from typing import Callable, List, Optional, Tuple2import typing34import httpcore54from .._models import Request5from .base import AsyncBaseTransport, BaseTransport679class MockTransport(httpcore.SyncHTTPTransport, httpcore.AsyncHTTPTransport):10 def __init__(self, handler: Callable) -> None:8class MockTransport(AsyncBaseTransport, BaseTransport):9 def __init__(self, handler: typing.Callable) -> None:10 self.handler = handler1113 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 lines
30 return (31 response.status_code,32 response.headers.raw,33 response.stream,33 response.ext,34 response.extensions,35 )3636 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 lines
65 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 line
2import itertools3import typing4from urllib.parse import unquote56import httpcore6from .base import BaseTransport789def _skip_leading_empty_chunks(body: typing.Iterable) -> typing.Iterable:10 body = iter(body)
2 unmodified lines
13 return itertools.chain([chunk], body)14 return []151617class WSGITransport(httpcore.SyncHTTPTransport):17class 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 lines
58 self.raise_app_exceptions = raise_app_exceptions59 self.script_name = script_name60 self.remote_addr = remote_addr6162 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))7374 scheme, host, port, full_path = url75 path, _, query = full_path.partition(b"?")76 if port is None:
1 unmodified line
7879 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 lines
124 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 = {}129132 return (status_code, headers, stream, ext)130 return (status_code, headers, result, extensions)
modified:httpx/__init__.py+3 added
34 unmodified lines
35)36from ._models import URL, Cookies, Headers, QueryParams, Request, Response37from ._status_codes import StatusCode, codes38from ._transports.asgi import ASGITransport39from ._transports.base import AsyncBaseTransport, BaseTransport40from ._transports.default import AsyncHTTPTransport, HTTPTransport41from ._transports.mock import MockTransport42from ._transports.wsgi import WSGITransport43
1 unmodified line
45 "__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 lines
modified:httpx/_client.py+97 added-91 removed
2 unmodified lines
3import typing4import warnings5from types import TracebackType67import httpcore87from .__version__ import __version__8from ._auth import Auth, BasicAuth, FunctionAuth9from ._config import (10 DEFAULT_LIMITS,
6 unmodified lines
17 UnsetType,18)19from ._decoders import SUPPORTED_DECODERS20from ._exceptions import (23 HTTPCORE_EXC_MAP,21 InvalidURL,22 RemoteProtocolError,23 TooManyRedirects,27 map_exceptions,24 request_context,25)26from ._models import URL, Cookies, Headers, QueryParams, Request, Response27from ._status_codes import codes28from ._transports.asgi import ASGITransport29from ._transports.base import AsyncBaseTransport, BaseTransport30from ._transports.default import AsyncHTTPTransport, HTTPTransport31from ._transports.wsgi import WSGITransport32from ._types import (33 AuthTypes,
532 unmodified lines
566 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 lines
617 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 lines
643 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 transport653654 if app is not None:
10 unmodified lines
665 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 line
675 trust_env=trust_env,676 proxy=proxy,677 )678683 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 lines
770 timeout=timeout,771 allow_redirects=allow_redirects,772 history=[],773 )778779 if not stream:780 try:774 try:775 if not stream:776 response.read()782 finally:783 response.close()777785 try:778 for hook in self._event_hooks["response"]:779 hook(response)788 except Exception:789 response.close()790 raise780792 return response781 return response782783 except Exception as exc:784 response.close()785 raise exc786787 def _send_handling_auth(788 self,789 request: Request,790 auth: Auth,
14 unmodified lines
805 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 response813814 response.history = list(history)815 response.read()816 request = next_request817 history.append(response)818819 except Exception as exc:820 response.close()821 raise exc822823 def _send_handling_redirects(824 self,825 request: Request,826 timeout: Timeout,
6 unmodified lines
833 "Exceeded maximum allowed redirects.", request=request834 )835836 response = self._send_single_request(request, timeout)837 try:842 response.history = list(history)838 response.history = list(history)839844 if not response.is_redirect:845 return response840 if not response.is_redirect:841 return response842847 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]845852 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 response851852 except Exception as exc:853 response.close()854 raise exc855856 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()863864 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 )872873 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"]()877878 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 lines
1201 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 lines
1253 app=app,1254 trust_env=trust_env,1255 )12561257 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 lines
1278 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 transport12881289 if app is not None:
10 unmodified lines
1300 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 line
1310 trust_env=trust_env,1311 proxy=proxy,1312 )13131316 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 lines
1406 timeout=timeout,1407 allow_redirects=allow_redirects,1408 history=[],1409 )14121413 if not stream:1414 try:1410 try:1411 if not stream:1412 await response.aread()1416 finally:1417 await response.aclose()14131419 try:1414 for hook in self._event_hooks["response"]:1415 await hook(response)1422 except Exception:1423 await response.aclose()1424 raise14161426 return response1417 return response14181419 except Exception as exc:1420 await response.aclose()1421 raise exc14221423 async def _send_handling_auth(1424 self,1425 request: Request,1426 auth: Auth,
14 unmodified lines
1441 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 response14491450 response.history = list(history)1451 await response.aread()1452 request = next_request1453 history.append(response)14541455 except Exception as exc:1456 await response.aclose()1457 raise exc14581459 async def _send_handling_redirects(1460 self,1461 request: Request,1462 timeout: Timeout,
6 unmodified lines
1469 "Exceeded maximum allowed redirects.", request=request1470 )14711472 response = await self._send_single_request(request, timeout)1473 try:1476 response.history = list(history)1474 response.history = list(history)14751478 if not response.is_redirect:1479 return response1476 if not response.is_redirect:1477 return response14781481 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]14811486 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 response14871488 except Exception as exc:1489 await response.aclose()1490 raise exc14911492 async def _send_single_request(1493 self, request: Request, timeout: Timeout1494 ) -> Response:1495 """
2 unmodified lines
1498 transport = self._transport_for_url(request.url)1499 timer = Timer()1500 await timer.async_start()15011500 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 )15151516 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"]()15201521 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 lines
modified:httpx/_decoders.py+8 added-6 removed
6 unmodified lines
7import io8import typing9import zlib1011from ._exceptions import DecodingError1213try:14 import brotli15except ImportError: # pragma: nocover16 brotli = None
38 unmodified lines
55 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 exc6061 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 exc666768class GZipDecoder(ContentDecoder):69 """
8 unmodified lines
78 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 exc8384 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 exc899091class BrotliDecoder(ContentDecoder):92 """
26 unmodified lines
119 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 exc124125 def flush(self) -> bytes:126 if not self.seen_data:127 return b""
1 unmodified line
129 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 exc134135136class MultiDecoder(ContentDecoder):137 """
232 unmodified lines
modified:httpx/_exceptions.py+31 added-49 removed
32 unmodified lines
33"""34import contextlib35import typing3637import httpcore3837if typing.TYPE_CHECKING:38 from ._models import Request, Response # pragma: nocover3940
14 unmodified lines
55 print(f"HTTP Exception for {exc.request.url} - {exc}")56 ```57 """5861 def __init__(self, message: str, *, request: "Request") -> None:59 def __init__(self, message: str) -> None:60 super().__init__(message)63 self.request = request616263class RequestError(HTTPError):64 """65 Base class for all exceptions that may occur when issuing a `.request()`.66 """6771 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 = request7778 @property79 def request(self) -> "Request":80 if self._request is None:81 raise RuntimeError("The .request property has not been set.")82 return self._request8384 @request.setter85 def request(self, request: "Request") -> None:86 self._request = request878889class TransportError(RequestError):90 """91 Base class for all exceptions that occur at the level of the Transport API.7879 All of these exceptions also have an equivelent mapping in `httpcore`.92 """939495# Timeout exceptions...
134 unmodified lines
230231 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 = response237238239class InvalidURL(Exception):
90 unmodified lines
330 super().__init__(message)331332333@contextlib.contextmanager321def map_exceptions(322 mapping: typing.Mapping[typing.Type[Exception], typing.Type[Exception]],323 **kwargs: typing.Any,324) -> typing.Iterator[None]:334def 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 = None329330 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_exc338339 if mapped_exc is None:340 raise341342 message = str(exc)343 raise mapped_exc(message, **kwargs) from exc # type: ignore344345346HTTPCORE_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 exc
modified:httpx/_models.py+23 added-29 removed
1import cgi2import contextlib2import datetime3import email.message4import json as jsonlib5import typing
16 unmodified lines
22 TextChunker,23 TextDecoder,24)25from ._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)35from ._status_codes import codes36from ._types import (37 ByteStream,
867 unmodified lines
905 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_code
6 unmodified lines
920 self.next_request: typing.Optional[Request] = None921922 self.call_next: typing.Optional[typing.Callable] = None923927 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_close927928 self.is_closed = False
62 unmodified lines
991 self._request = value992993 @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"9991000 @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)10061007 @property1008 def url(self) -> typing.Optional[URL]:1009 """
144 unmodified lines
11541155 def __repr__(self) -> str:1156 return f"<Response [{self.status_code} {self.reason_phrase}]>"11571155 @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 exc11651158 def read(self) -> bytes:1159 """1160 Read and return the response content.1161 """
12 unmodified lines
1174 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 chunk
10 unmodified lines
1193 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 chunk
4 unmodified lines
1206 yield chunk12071208 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 lines
1228 self.is_stream_consumed = True1229 self._num_bytes_downloaded = 01230 chunker = ByteChunker(chunk_size=chunk_size)12311240 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 chunk
10 unmodified lines
1247 """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)12531254 async def aread(self) -> bytes:1255 """1256 Read and return the response content.
13 unmodified lines
1270 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 chunk
10 unmodified lines
1289 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 chunk
4 unmodified lines
1302 yield chunk13031304 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 lines
1324 self.is_stream_consumed = True1325 self._num_bytes_downloaded = 01326 chunker = ByteChunker(chunk_size=chunk_size)13271335 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 chunk
10 unmodified lines
1343 """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)134913501351class Cookies(MutableMapping):1352 """
187 unmodified lines
modified:tests/client/test_async_client.py+4 added-24 removed
1import typing2from datetime import timedelta34import httpcore4import pytest56import httpx7
159 unmodified lines
167168169@pytest.mark.usefixtures("async_environment")170async def test_context_managed_transport():172 class Transport(httpcore.AsyncHTTPTransport):171 class Transport(httpx.AsyncBaseTransport):172 def __init__(self):173 self.events = []174175 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 lines
199200201@pytest.mark.usefixtures("async_environment")202async 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] = []207208 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 lines
302 assert response.json() == {"app": "mounted"}303304305@pytest.mark.usefixtures("async_environment")307async def test_response_aclose_map_exceptions():308 class BrokenStream:309 async def __aiter__(self):310 # so we're an AsyncIterator311 pass # pragma: nocover312313 async def aclose(self):314 raise httpcore.CloseError(OSError(104, "Connection reset by peer"))315316 def handle(request: httpx.Request) -> httpx.Response:317 return httpx.Response(200, stream=BrokenStream())318319 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()323324325@pytest.mark.usefixtures("async_environment")306async def test_async_mock_transport():307 async def hello_world(request):308 return httpx.Response(200, text="Hello, world!")309
6 unmodified lines
modified:tests/client/test_client.py+4 added-5 removed
1import typing2from datetime import timedelta34import httpcore4import pytest56import httpx7
214 unmodified lines
222 httpx.AsyncClient(pool_limits=limits)223224225def test_context_managed_transport():227 class Transport(httpcore.SyncHTTPTransport):226 class Transport(httpx.BaseTransport):227 def __init__(self):228 self.events = []229230 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 lines
253 ]254255256def 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] = []261262 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 lines
modified:tests/client/test_redirects.py+8 added-4 removed
1import httpcore1import pytest23import httpx456def 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.")910 if request.url.path == "/redirect_301":11 status_code = httpx.codes.MOVED_PERMANENTLY12 content = b"<a href='https://example.org/'>here</a>"
379 unmodified lines
392 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."396397398@pytest.mark.usefixtures("async_environment")399async 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 lines
732 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()738739740@pytest.mark.parametrize(
25 unmodified lines
766def 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 lines
787def 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)793794795def test_response_with_unset_request():
39 unmodified lines
modified:tests/conftest.py-15 removed
74 unmodified lines
75async 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 lines
110 )111 await send({"type": "http.response.body", "body": b"Hello, world!"})112113116async 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 )124125 await sleep(1)126 await send({"type": "http.response.body", "body": b"", "more_body": False})127128114async def status_code(scope, receive, send):115 status_code = int(scope["path"].replace("/status/", ""))116 await send(117 {
175 unmodified lines
modified:tests/test_asgi.py+36 added
68 unmodified lines
69 await send({"type": "http.response.body", "body": output})70 raise RuntimeError()717273async def empty_stream():74 yield b""757677@pytest.mark.usefixtures("async_environment")78async 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])8889 assert status_code == 20090 assert body == b"Hello, World!"919293@pytest.mark.usefixtures("async_environment")94async 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])104105 assert status_code == 200106 assert body == b""107108109@pytest.mark.usefixtures("async_environment")110async 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 lines
modified:tests/test_decoders.py+1 added-1 removed
168 unmodified lines
169 with pytest.raises(httpx.DecodingError):170 request = httpx.Request("GET", "https://example.org")171 httpx.Response(200, headers=headers, content=compressed_body, request=request)172173 with pytest.raises(ValueError):173 with pytest.raises(httpx.DecodingError):174 httpx.Response(200, headers=headers, content=compressed_body)175176177@pytest.mark.parametrize(
181 unmodified lines
modified:tests/test_exceptions.py+45 added-18 removed
1from typing import Any1from unittest import mock23import httpcore4import pytest56import httpx7from httpx._exceptions import HTTPCORE_EXC_MAP7from httpx._transports.default import HTTPCORE_EXC_MAP8910def test_httpcore_all_exceptions_mapped() -> None:11 """
16 unmodified lines
28 """29 HTTPCore exception mapping works as expected.30 """3132 # 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()3436 # 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()3843 # 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 pass4148 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""4546 def close(self):47 raise httpcore.CloseError()4849 with mock.patch("httpcore.SyncConnectionPool.request", side_effect=connect_failed):50 with pytest.raises(httpx.ConnectError):51 httpx.get(server.url)5253 with mock.patch(54 "httpcore.SyncConnectionPool.request",55 return_value=(200, [], TimeoutStream(), {}),56 ):57 with pytest.raises(httpx.ReadTimeout):58 httpx.get(server.url)5960 with mock.patch(61 "httpcore.SyncConnectionPool.request",62 return_value=(200, [], CloseFailedStream(), {}),63 ):64 with pytest.raises(httpx.CloseError):65 httpx.get(server.url)666768def test_httpx_exceptions_exposed() -> None:69 """70 All exception classes defined in `httpx._exceptions`71 are exposed as public API.
8 unmodified lines
80 ]8182 if not_exposed: # pragma: nocover83 pytest.fail(f"Unexposed HTTPX exceptions: {not_exposed}")848586def test_request_attribute() -> None:87 # Exception without request attribute88 exc = httpx.ReadTimeout("Read operation timed out")89 with pytest.raises(RuntimeError):90 exc.request9192 # 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 == request
modified:CHANGELOG.md+19 added-2 removed
2 unmodified lines
3All notable changes to this project will be documented in this file.45The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).67## 0.17.17## Master89The 0.18.x release series formalises our low-level Transport API, introducing the10base classes `httpx.BaseTransport` and `httpx.AsyncBaseTransport`.1112See the "Writing custom transports" documentation and the `httpx.BaseTransport.handle_request()`13docstring for more complete details on implementing custom transports.1415Pull request #1522 includes a checklist of differences from the previous `httpcore` transport API,16for developers implementing custom transports.1718### Changed1920* 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`.2324## 0.17.1 (March 15th, 2021)2526### Fixed2728* Type annotation on `CertTypes` allows `keyfile` and `password` to be optional. (Pull #1503)29* Fix httpcore pinned version. (Pull #1495)3014## 0.17.031## 0.17.0 (February 28th, 2021)3233### Added3435* Add `httpx.MockTransport()`, allowing to mock out a transport using pre-determined responses. (Pull #1401, Pull #1449)
712 unmodified lines