Skip to content
Myr

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

10 files+70 added−50 removed

modified:httpx/dispatch/http11.py+1 added-1 removed
129 unmodified lines
130 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.headers135136 async def _receive_response_data(137 self, timeout: TimeoutConfig = None138 ) -> typing.AsyncIterator[bytes]:
49 unmodified lines
modified:httpx/dispatch/http2.py+1 added-1 removed
131 unmodified lines
132 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, headers137138 async def body_iter(139 self, stream_id: int, timeout: TimeoutConfig = None140 ) -> typing.AsyncIterator[bytes]:
37 unmodified lines
modified:httpx/client.py+24 added-15 removed
22 unmodified lines
23 InvalidURL,24 RedirectBodyUnavailable,25 RedirectLoop,26 TooManyRedirects,27 HTTPError,28)29from .interfaces import AsyncDispatcher, ConcurrencyBackend, Dispatcher30from .models import (31 URL,
50 unmodified lines
82 app=app, raise_app_exceptions=raise_app_exceptions83 )8485 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 = dispatch
70 unmodified lines
167 if isinstance(auth, tuple):168 auth = HTTPBasicAuth(username=auth[0], password=auth[1])169 request = auth(request)170171 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 raise183184 if not stream:185 try:186 await response.read()
18 unmodified lines
205 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])212213 response = await self.dispatch.send(214 request, verify=verify, cert=cert, timeout=timeout215 )216217 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)223224 if allow_redirects and response.is_redirect:225 request = self.build_redirect_request(request, response)226 else:
28 unmodified lines
255 ) -> 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 lines
313 if url.origin != request.url.origin:314 del headers["Authorization"]315 return headers316310 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.content328329330class AsyncClient(BaseClient):
639 unmodified lines
modified:httpx/concurrency.py+1 added-1 removed
221 unmodified lines
222 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_11225226 return (reader, writer, protocol)226 return reader, writer, protocol227228 async def run_in_threadpool(229 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any230 ) -> typing.Any:
44 unmodified lines
modified:httpx/exceptions.py+27 added-16 removed
1from typing import TYPE_CHECKING23if TYPE_CHECKING:4 from .models import BaseRequest, BaseResponse # pragma: nocover567class HTTPError(Exception):8 """9 Base class for Httpx exception10 """1112 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)161718# Timeout exceptions...19204class Timeout(Exception):21class Timeout(HTTPError):22 """23 A base class for all timeouts.24 """25
24 unmodified lines
5051# HTTP exceptions...525337class HttpError(Exception):54class ProtocolError(HTTPError):55 """39 An HTTP error occurred.40 """414243class ProtocolError(Exception):44 """56 Malformed HTTP.57 """585949class DecodingError(Exception):60class DecodingError(HTTPError):61 """62 Decoding of the response failed.63 """646566# Redirect exceptions...676858class RedirectError(Exception):69class RedirectError(HTTPError):70 """71 Base class for HTTP redirect errors.72 """73
19 unmodified lines
9394# Stream exceptions...959686class StreamException(Exception):97class StreamError(HTTPError):98 """99 The base class for stream exceptions.100101 The developer made an error in accessing the request stream in102 an invalid way.103 """10410595class StreamConsumed(StreamException):106class StreamConsumed(StreamError):107 """108 Attempted to read or stream response content, but the content has already109 been streamed.110 """111112102class ResponseNotRead(StreamException):113class ResponseNotRead(StreamError):114 """115 Attempted to access response content, without having called `read()`116 after a streaming response.117 """118119109class ResponseClosed(StreamException):120class ResponseClosed(StreamError):121 """122 Attempted to read or stream response content, but the request has been123 closed.124 """
1 unmodified line
126127# Other cases...128129119class InvalidURL(Exception):130class InvalidURL(HTTPError):131 """132 URL was missing a hostname, or was not one of HTTP/HTTPS.133 """134135125class CookieConflict(Exception):136class 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 lines
25class AsyncDispatcher:26 """27 Base class for async dispatcher classes, that handle sending the request.2829 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 lines
717273class 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.7677 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 lines
135136137class 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 lines
154class BasePoolSemaphore:155 """156 A semaphore for use with connection pooling.157158 Abstracts away any asyncio-specfic interfaces.158 Abstracts away any asyncio-specific interfaces.159 """160161 async def acquire(self) -> None:162 raise NotImplementedError() # pragma: no cover
68 unmodified lines
modified:httpx/models.py+6 added-7 removed
18 unmodified lines
19 MultiDecoder,20)21from .exceptions import (22 CookieConflict,23 HttpError,23 HTTPError,24 InvalidURL,25 ResponseClosed,26 ResponseNotRead,27 StreamConsumed,
499 unmodified lines
527 content_type = ""528 return content, content_type529530 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)533534 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]534 auto_headers: typing.List[typing.Tuple[bytes, bytes]] = []535536 has_host = "host" in self.headers537 has_user_agent = "user-agent" in self.headers538 has_accept = "accept" in self.headers
147 unmodified lines
686 self.headers = Headers(headers)687688 self.request = request689 self.on_close = on_close690 self.next = None # typing.Optional[typing.Callable]690 self.next: typing.Optional[typing.Callable] = None691692 @property693 def reason_phrase(self) -> str:694 return StatusCode.get_reason_phrase(self.status_code)
80 unmodified lines
775 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 lines
810 elif StatusCode.is_server_error(self.status_code):811 message = message.format(self, error_type="Server Error")812 else:813 message = ""814814 if message:816 raise HttpError(message)815 raise HTTPError(message, response=self)816817 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 lines
modified:tests/client/test_async_client.py+2 added-1 removed
70 unmodified lines
71 "GET", f"http://127.0.0.1:8000/status/{status_code}"72 )7374 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 None8081
54 unmodified lines
modified:tests/client/test_client.py+2 added-2 removed
93 unmodified lines
94 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 )9898 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 None104105
55 unmodified lines
modified:tests/dispatch/utils.py+1 added-1 removed
27 unmodified lines
28 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_2333435class MockHTTP2Server(BaseReader, BaseWriter):36 """
86 unmodified lines