Added base class HTTPError with request/response attribute (#162)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by halbow · committed by Seth Michael Larson · parent 9142a89 · Browse files · 10 files·+70 added−50 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+70 added−50 removed
- tests:+5 added−4 removed
- other:+65 added−46 removed
Provenance
- Commit
92fbe5f- Tree
9565f6f- Author
halbow <39669025+halbow@users.noreply.github.com>- Committer
Seth Michael Larson <sethmichaellarson@gmail.com>- Parent
9142a89
10 files changed+70 added−50 removed
modified:httpx/dispatch/http11.py+1 added-1 removed
129 unmodified lines130 else:131 assert isinstance(event, h11.Response)132 break133 http_version = "HTTP/%s" % event.http_version.decode("latin-1", errors="ignore")134- return (http_version, event.status_code, event.headers)134+ return http_version, event.status_code, event.headers135 136 async def _receive_response_data(137 self, timeout: TimeoutConfig = None138 ) -> typing.AsyncIterator[bytes]:49 unmodified linesmodified:httpx/dispatch/http2.py+1 added-1 removed
131 unmodified lines132 if k == b":status":133 status_code = int(v.decode("ascii", errors="ignore"))134 elif not k.startswith(b":"):135 headers.append((k, v))136- return (status_code, headers)136+ return status_code, headers137 138 async def body_iter(139 self, stream_id: int, timeout: TimeoutConfig = None140 ) -> typing.AsyncIterator[bytes]:37 unmodified linesmodified:httpx/client.py+24 added-15 removed
22 unmodified lines23 InvalidURL,24 RedirectBodyUnavailable,25 RedirectLoop,26 TooManyRedirects,27+ HTTPError,28 )29 from .interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher30 from .models import (31 URL,50 unmodified lines82 app=app, raise_app_exceptions=raise_app_exceptions83 )84 85 if dispatch is None:85- async_dispatch = ConnectionPool(86+ async_dispatch: AsyncDispatcher = ConnectionPool(87 verify=verify,88 cert=cert,89 timeout=timeout,90 pool_limits=pool_limits,91 backend=backend,91- ) # type: AsyncDispatcher92+ )93 elif isinstance(dispatch, Dispatcher):94 async_dispatch = ThreadedDispatcher(dispatch, backend)95 else:96 async_dispatch = dispatch70 unmodified lines167 if isinstance(auth, tuple):168 auth = HTTPBasicAuth(username=auth[0], password=auth[1])169 request = auth(request)170 171+ try:170- response = await self.send_handling_redirects(171- request,172- verify=verify,173- cert=cert,174- timeout=timeout,175- allow_redirects=allow_redirects,176- )172+ response = await self.send_handling_redirects(173+ request,174+ verify=verify,175+ cert=cert,176+ timeout=timeout,177+ allow_redirects=allow_redirects,178+ )179+ except HTTPError as exc:180+ # Add the original request to any HTTPError181+ exc.request = request182+ raise183 184 if not stream:185 try:186 await response.read()18 unmodified lines205 while True:206 # We perform these checks here, so that calls to `response.next()`207 # will raise redirect errors if appropriate.208 if len(history) > self.max_redirects:203- raise TooManyRedirects()209+ raise TooManyRedirects(response=history[-1])210 if request.url in [response.url for response in history]:205- raise RedirectLoop()211+ raise RedirectLoop(response=history[-1])212 213 response = await self.dispatch.send(214 request, verify=verify, cert=cert, timeout=timeout215 )216+217 should_close_response = True218 try:219 assert isinstance(response, AsyncResponse)220 response.history = list(history)221 self.cookies.extract_cookies(response)215- history = history + [response]222+ history.append(response)223 224 if allow_redirects and response.is_redirect:225 request = self.build_redirect_request(request, response)226 else:28 unmodified lines255 ) -> AsyncRequest:256 method = self.redirect_method(request, response)257 url = self.redirect_url(request, response)258 headers = self.redirect_headers(request, url)252- content = self.redirect_content(request, method)259+ content = self.redirect_content(request, method, response)260 cookies = self.merge_cookies(request.cookies)261 return AsyncRequest(262 method=method, url=url, headers=headers, data=content, cookies=cookies263 )49 unmodified lines313 if url.origin != request.url.origin:314 del headers["Authorization"]315 return headers316 310- def redirect_content(self, request: AsyncRequest, method: str) -> bytes:317+ def redirect_content(318+ self, request: AsyncRequest, method: str, response: AsyncResponse319+ ) -> bytes:320 """321 Return the body that should be used for the redirect request.322 """323 if method != request.method and method == "GET":324 return b""325 if request.is_streaming:317- raise RedirectBodyUnavailable()326+ raise RedirectBodyUnavailable(response=response)327 return request.content328 329 330 class AsyncClient(BaseClient):639 unmodified linesmodified:httpx/concurrency.py+1 added-1 removed
221 unmodified lines222 reader = Reader(stream_reader=stream_reader, timeout=timeout)223 writer = Writer(stream_writer=stream_writer, timeout=timeout)224 protocol = Protocol.HTTP_2 if ident == "h2" else Protocol.HTTP_11225 226- return (reader, writer, protocol)226+ return reader, writer, protocol227 228 async def run_in_threadpool(229 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any230 ) -> typing.Any:44 unmodified linesmodified:httpx/exceptions.py+27 added-16 removed
1+from typing import TYPE_CHECKING2+3+if TYPE_CHECKING:4+ from .models import BaseRequest, BaseResponse # pragma: nocover5+6+7+class HTTPError(Exception):8+ """9+ Base class for Httpx exception10+ """11+12+ def __init__(self, request: 'BaseRequest' = None, response: 'BaseResponse' = None, *args) -> None:13+ self.response = response14+ self.request = request or getattr(self.response, "request", None)15+ super().__init__(*args)16+17+18 # Timeout exceptions...19 20 4-class Timeout(Exception):21+class Timeout(HTTPError):22 """23 A base class for all timeouts.24 """25 24 unmodified lines50 51 # HTTP exceptions...52 53 37-class HttpError(Exception):54+class ProtocolError(HTTPError):55 """39- An HTTP error occurred.40- """41-42-43-class ProtocolError(Exception):44- """56 Malformed HTTP.57 """58 59 49-class DecodingError(Exception):60+class DecodingError(HTTPError):61 """62 Decoding of the response failed.63 """64 65 66 # Redirect exceptions...67 68 58-class RedirectError(Exception):69+class RedirectError(HTTPError):70 """71 Base class for HTTP redirect errors.72 """73 19 unmodified lines93 94 # Stream exceptions...95 96 86-class StreamException(Exception):97+class StreamError(HTTPError):98 """99 The base class for stream exceptions.100 101 The developer made an error in accessing the request stream in102 an invalid way.103 """104 105 95-class StreamConsumed(StreamException):106+class StreamConsumed(StreamError):107 """108 Attempted to read or stream response content, but the content has already109 been streamed.110 """111 112 102-class ResponseNotRead(StreamException):113+class ResponseNotRead(StreamError):114 """115 Attempted to access response content, without having called `read()`116 after a streaming response.117 """118 119 109-class ResponseClosed(StreamException):120+class ResponseClosed(StreamError):121 """122 Attempted to read or stream response content, but the request has been123 closed.124 """1 unmodified line126 127 # Other cases...128 129 119-class InvalidURL(Exception):130+class InvalidURL(HTTPError):131 """132 URL was missing a hostname, or was not one of HTTP/HTTPS.133 """134 135 125-class CookieConflict(Exception):136+class CookieConflict(HTTPError):137 """138 Attempted to lookup a cookie by name, but multiple cookies existed.139 """modified:httpx/interfaces.py+5 added-5 removed
24 unmodified lines25 class AsyncDispatcher:26 """27 Base class for async dispatcher classes, that handle sending the request.28 29- Stubs out the interface, as well as providing a `.request()` convienence29+ Stubs out the interface, as well as providing a `.request()` convenience30 implementation, to make it easy to use or test stand-alone dispatchers,31 without requiring a complete `Client` instance.32 """33 37 unmodified lines71 72 73 class Dispatcher:74 """75- Base class for syncronous dispatcher classes, that handle sending the request.75+ Base class for synchronous dispatcher classes, that handle sending the request.76 77- Stubs out the interface, as well as providing a `.request()` convienence77+ Stubs out the interface, as well as providing a `.request()` convenience78 implementation, to make it easy to use or test stand-alone dispatchers,79 without requiring a complete `Client` instance.80 """81 53 unmodified lines135 136 137 class BaseWriter:138 """139- A stream writer. Abstracts away any asyncio-specfic interfaces139+ A stream writer. Abstracts away any asyncio-specific interfaces140 into a more generic base class, that we can use with alternate141 backend, or for stand-alone test cases.142 """143 10 unmodified lines154 class BasePoolSemaphore:155 """156 A semaphore for use with connection pooling.157 158- Abstracts away any asyncio-specfic interfaces.158+ Abstracts away any asyncio-specific interfaces.159 """160 161 async def acquire(self) -> None:162 raise NotImplementedError() # pragma: no cover68 unmodified linesmodified:httpx/models.py+6 added-7 removed
18 unmodified lines19 MultiDecoder,20 )21 from .exceptions import (22 CookieConflict,23- HttpError,23+ HTTPError,24 InvalidURL,25 ResponseClosed,26 ResponseNotRead,27 StreamConsumed,499 unmodified lines527 content_type = ""528 return content, content_type529 530 def prepare(self) -> None:531- content = getattr(self, "content", None) # type: bytes531+ content: typing.Optional[bytes] = getattr(self, "content", None)532 is_streaming = getattr(self, "is_streaming", False)533 534- auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]534+ auto_headers: typing.List[typing.Tuple[bytes, bytes]] = []535 536 has_host = "host" in self.headers537 has_user_agent = "user-agent" in self.headers538 has_accept = "accept" in self.headers147 unmodified lines686 self.headers = Headers(headers)687 688 self.request = request689 self.on_close = on_close690- self.next = None # typing.Optional[typing.Callable]690+ self.next: typing.Optional[typing.Callable] = None691 692 @property693 def reason_phrase(self) -> str:694 return StatusCode.get_reason_phrase(self.status_code)80 unmodified lines775 Returns a decoder instance which can be used to decode the raw byte776 content, depending on the Content-Encoding used in the response.777 """778 if not hasattr(self, "_decoder"):779- decoders = [] # type: typing.List[Decoder]779+ decoders: typing.List[Decoder] = []780 values = self.headers.getlist("content-encoding", split_commas=True)781 for value in values:782 value = value.strip().lower()783 decoder_cls = SUPPORTED_DECODERS[value]26 unmodified lines810 elif StatusCode.is_server_error(self.status_code):811 message = message.format(self, error_type="Server Error")812 else:813 message = ""814-814 if message:816- raise HttpError(message)815+ raise HTTPError(message, response=self)816 817 def json(self, **kwargs: typing.Any) -> typing.Union[dict, list]:818 if self.charset_encoding is None and self.content and len(self.content) > 3:819 encoding = guess_json_utf(self.content)350 unmodified linesmodified:tests/client/test_async_client.py+2 added-1 removed
70 unmodified lines71 "GET", f"http://127.0.0.1:8000/status/{status_code}"72 )73 74 if 400 <= status_code < 600:75- with pytest.raises(httpx.exceptions.HttpError):75+ with pytest.raises(httpx.exceptions.HTTPError) as exc_info:76 response.raise_for_status()77+ assert exc_info.value.response == response78 else:79 assert response.raise_for_status() is None80 81 54 unmodified linesmodified:tests/client/test_client.py+2 added-2 removed
93 unmodified lines94 for status_code in (200, 400, 404, 500, 505):95 response = client.request(96 "GET", "http://127.0.0.1:8000/status/{}".format(status_code)97 )98-98 if 400 <= status_code < 600:100- with pytest.raises(httpx.exceptions.HttpError):99+ with pytest.raises(httpx.exceptions.HTTPError) as exc_info:100 response.raise_for_status()101+ assert exc_info.value.response == response102 else:103 assert response.raise_for_status() is None104 105 55 unmodified linesmodified:tests/dispatch/utils.py+1 added-1 removed
27 unmodified lines28 ssl_context: typing.Optional[ssl.SSLContext],29 timeout: TimeoutConfig,30 ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:31 self.server = MockHTTP2Server(self.app)32- return (self.server, self.server, Protocol.HTTP_2)32+ return self.server, self.server, Protocol.HTTP_233 34 35 class MockHTTP2Server(BaseReader, BaseWriter):36 """86 unmodified lines