Skip to content
Myr

Make the response's request parameter optional (#1238)

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

* Make the response's request parameter optional * Fix _models coverage * Move DecodingError in _models * Update httpx/_models.py * Update _models.py * Update test_responses.py * Update test_responses.py

authored by tbascoul · committed by GitHub · parent 33d339a · Browse files · 4 files+171 added−66 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: Tom Christie <tom@tomchristie.com>

Diff stats

4 files+171 added−66 removed

  • tests:+82 added−8 removed
  • other:+89 added−58 removed

4 files+171 added−66 removed

modified:httpx/_decoders.py+13 added-26 removed
7 unmodified lines
8import zlib910import chardet1112from ._exceptions import DecodingError1312try:13 import brotli14except ImportError: # pragma: nocover15 brotli = None1619if typing.TYPE_CHECKING: # pragma: no cover20 from ._models import Request172218class Decoder:24 def __init__(self, request: "Request") -> None:25 self.request = request2619 def decode(self, data: bytes) -> bytes:20 raise NotImplementedError() # pragma: nocover2122 def flush(self) -> bytes:
18 unmodified lines
4142 See: https://stackoverflow.com/questions/183869943 """4453 def __init__(self, request: "Request") -> None:54 self.request = request45 def __init__(self) -> None:46 self.first_attempt = True47 self.decompressor = zlib.decompressobj()4849 def decode(self, data: bytes) -> bytes:
4 unmodified lines
54 except zlib.error as exc:55 if was_first_attempt:56 self.decompressor = zlib.decompressobj(-zlib.MAX_WBITS)57 return self.decode(data)67 raise DecodingError(message=str(exc), request=self.request)58 raise ValueError(str(exc))5960 def flush(self) -> bytes:61 try:62 return self.decompressor.flush()63 except zlib.error as exc: # pragma: nocover73 raise DecodingError(message=str(exc), request=self.request)64 raise ValueError(str(exc))656667class GZipDecoder(Decoder):68 """
1 unmodified line
7071 See: https://stackoverflow.com/questions/183869972 """7383 def __init__(self, request: "Request") -> None:84 self.request = request74 def __init__(self) -> None:75 self.decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)7677 def decode(self, data: bytes) -> bytes:78 try:79 return self.decompressor.decompress(data)80 except zlib.error as exc:91 raise DecodingError(message=str(exc), request=self.request)81 raise ValueError(str(exc))8283 def flush(self) -> bytes:84 try:85 return self.decompressor.flush()86 except zlib.error as exc: # pragma: nocover97 raise DecodingError(message=str(exc), request=self.request)87 raise ValueError(str(exc))888990class BrotliDecoder(Decoder):91 """
4 unmodified lines
96 Supports both 'brotlipy' and 'Brotli' packages since they share an import97 name. The top branches are for 'brotlipy' and bottom branches for 'Brotli'98 """99110 def __init__(self, request: "Request") -> None:100 def __init__(self) -> None:101 if brotli is None: # pragma: nocover102 raise ImportError(103 "Using 'BrotliDecoder', but the 'brotlipy' or 'brotli' library "104 "is not installed."105 "Make sure to install httpx using `pip install httpx[brotli]`."106 ) from None107118 self.request = request108 self.decompressor = brotli.Decompressor()109 self.seen_data = False110 if hasattr(self.decompressor, "decompress"):111 self._decompress = self.decompressor.decompress
6 unmodified lines
118 self.seen_data = True119 try:120 return self._decompress(data)121 except brotli.error as exc:133 raise DecodingError(message=str(exc), request=self.request)122 raise ValueError(str(exc))123124 def flush(self) -> bytes:125 if not self.seen_data:126 return b""
1 unmodified line
128 if hasattr(self.decompressor, "finish"):129 self.decompressor.finish()130 return b""131 except brotli.error as exc: # pragma: nocover143 raise DecodingError(message=str(exc), request=self.request)132 raise ValueError(str(exc))133134135class MultiDecoder(Decoder):136 """
24 unmodified lines
161 """162 Handles incrementally decoding bytes into text163 """164176 def __init__(self, request: "Request", encoding: typing.Optional[str] = None):177 self.request = request165 def __init__(self, encoding: typing.Optional[str] = None):166 self.decoder: typing.Optional[codecs.IncrementalDecoder] = (167 None if encoding is None else codecs.getincrementaldecoder(encoding)()168 )169 self.detector = chardet.universaldetector.UniversalDetector()
26 unmodified lines
196 self.buffer = None197198 return text199 except UnicodeDecodeError as exc: # pragma: nocover212 raise DecodingError(message=str(exc), request=self.request)200 raise ValueError(str(exc))201202 def flush(self) -> str:203 try:204 if self.decoder is None:
4 unmodified lines
209 return bytes(self.buffer).decode(self._detector_result())210211 return self.decoder.decode(b"", True)212 except UnicodeDecodeError as exc: # pragma: nocover225 raise DecodingError(message=str(exc), request=self.request)213 raise ValueError(str(exc))214215 def _detector_result(self) -> str:216 self.detector.close()217 result = self.detector.result["encoding"]218 if not result: # pragma: nocover231 message = "Unable to determine encoding of content"232 raise DecodingError(message, request=self.request)219 raise ValueError("Unable to determine encoding of content")220221 return result222223
77 unmodified lines
modified:httpx/_models.py+76 added-32 removed
1import cgi2import contextlib3import datetime4import email.message5import json as jsonlib6import typing
19 unmodified lines
26)27from ._exceptions import (28 HTTPCORE_EXC_MAP,29 CookieConflict,30 DecodingError,31 HTTPStatusError,32 InvalidURL,33 NotRedirectResponse,34 RequestNotRead,
655 unmodified lines
690 def __init__(691 self,692 status_code: int,693 *,692 request: Request,694 request: Request = None,695 http_version: str = None,696 headers: HeaderTypes = None,697 stream: ContentStream = None,698 content: bytes = None,
2 unmodified lines
701 self.status_code = status_code702 self.http_version = http_version703 self.headers = Headers(headers)704703 self.request = request705 self._request: typing.Optional[Request] = request706707 self.call_next: typing.Optional[typing.Callable] = None708709 self.history = [] if history is None else list(history)710
18 unmodified lines
729 )730 return self._elapsed731732 @property733 def request(self) -> Request:734 """735 Returns the request instance associated to the current response.736 """737 if self._request is None:738 raise RuntimeError(739 "The request instance has not been set on this response."740 )741 return self._request742743 @request.setter744 def request(self, value: Request) -> None:745 self._request = value746747 @property748 def reason_phrase(self) -> str:749 return codes.get_reason_phrase(self.status_code)750751 @property
76 unmodified lines
828 for value in values:829 value = value.strip().lower()830 try:831 decoder_cls = SUPPORTED_DECODERS[value]814 decoders.append(decoder_cls(request=self.request))832 decoders.append(decoder_cls())833 except KeyError:834 continue835836 if len(decoders) == 1:837 self._decoder = decoders[0]838 elif len(decoders) > 1:839 self._decoder = MultiDecoder(children=decoders)840 else:823 self._decoder = IdentityDecoder(request=self.request)841 self._decoder = IdentityDecoder()842843 return self._decoder844845 @property
12 unmodified lines
858 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"859 "For more information check: https://httpstatuses.com/{0.status_code}"860 )861862 request = self._request863 if request is None:864 raise RuntimeError(865 "Cannot call `raise_for_status` as the request "866 "instance has not been set on this response."867 )868869 if codes.is_client_error(self.status_code):870 message = message.format(self, error_type="Client Error")846 raise HTTPStatusError(message, request=self.request, response=self)871 raise HTTPStatusError(message, request=request, response=self)872 elif codes.is_server_error(self.status_code):873 message = message.format(self, error_type="Server Error")849 raise HTTPStatusError(message, request=self.request, response=self)874 raise HTTPStatusError(message, request=request, response=self)875876 def json(self, **kwargs: typing.Any) -> typing.Any:877 if self.charset_encoding is None and self.content and len(self.content) > 3:878 encoding = guess_json_utf(self.content)
27 unmodified lines
906907 def __repr__(self) -> str:908 return f"<Response [{self.status_code} {self.reason_phrase}]>"909910 @contextlib.contextmanager911 def _wrap_decoder_errors(self) -> typing.Iterator[None]:912 # If the response has an associated request instance, we want decoding913 # errors to be raised as proper `httpx.DecodingError` exceptions.914 try:915 yield916 except ValueError as exc:917 if self._request is None:918 raise exc919 raise DecodingError(message=str(exc), request=self.request) from exc920921 def read(self) -> bytes:922 """923 Read and return the response content.924 """
8 unmodified lines
933 """934 if hasattr(self, "_content"):935 yield self._content936 else:937 with self._wrap_decoder_errors():901 for chunk in self.iter_raw():902 yield self.decoder.decode(chunk)903 yield self.decoder.flush()938 for chunk in self.iter_raw():939 yield self.decoder.decode(chunk)940 yield self.decoder.flush()941942 def iter_text(self) -> typing.Iterator[str]:943 """944 A str-iterator over the decoded response content945 that handles both gzip, deflate, etc but also detects the content's946 string encoding.947 """911 decoder = TextDecoder(request=self.request, encoding=self.charset_encoding)912 for chunk in self.iter_bytes():913 yield decoder.decode(chunk)914 yield decoder.flush()948 decoder = TextDecoder(encoding=self.charset_encoding)949 with self._wrap_decoder_errors():950 for chunk in self.iter_bytes():951 yield decoder.decode(chunk)952 yield decoder.flush()953954 def iter_lines(self) -> typing.Iterator[str]:955 decoder = LineDecoder()956 with self._wrap_decoder_errors():918 for text in self.iter_text():919 for line in decoder.decode(text):957 for text in self.iter_text():958 for line in decoder.decode(text):959 yield line960 for line in decoder.flush():961 yield line921 for line in decoder.flush():922 yield line962963 def iter_raw(self) -> typing.Iterator[bytes]:964 """965 A byte-iterator over the raw response content.
3 unmodified lines
969 if self.is_closed:970 raise ResponseClosed()971972 self.is_stream_consumed = True934 with map_exceptions(HTTPCORE_EXC_MAP, request=self.request):973 with map_exceptions(HTTPCORE_EXC_MAP, request=self._request):974 for part in self._raw_stream:975 yield part976 self.close()977
16 unmodified lines
994 Automatically called if the response body is read to completion.995 """996 if not self.is_closed:997 self.is_closed = True998 if self._request is not None:959 self._elapsed = self.request.timer.elapsed999 self._elapsed = self.request.timer.elapsed1000 self._raw_stream.close()10011002 async def aread(self) -> bytes:1003 """
10 unmodified lines
1014 """1015 if hasattr(self, "_content"):1016 yield self._content1017 else:1018 with self._wrap_decoder_errors():978 async for chunk in self.aiter_raw():979 yield self.decoder.decode(chunk)980 yield self.decoder.flush()1019 async for chunk in self.aiter_raw():1020 yield self.decoder.decode(chunk)1021 yield self.decoder.flush()10221023 async def aiter_text(self) -> typing.AsyncIterator[str]:1024 """1025 A str-iterator over the decoded response content1026 that handles both gzip, deflate, etc but also detects the content's1027 string encoding.1028 """988 decoder = TextDecoder(request=self.request, encoding=self.charset_encoding)989 async for chunk in self.aiter_bytes():990 yield decoder.decode(chunk)991 yield decoder.flush()1029 decoder = TextDecoder(encoding=self.charset_encoding)1030 with self._wrap_decoder_errors():1031 async for chunk in self.aiter_bytes():1032 yield decoder.decode(chunk)1033 yield decoder.flush()10341035 async def aiter_lines(self) -> typing.AsyncIterator[str]:1036 decoder = LineDecoder()1037 with self._wrap_decoder_errors():995 async for text in self.aiter_text():996 for line in decoder.decode(text):1038 async for text in self.aiter_text():1039 for line in decoder.decode(text):1040 yield line1041 for line in decoder.flush():1042 yield line998 for line in decoder.flush():999 yield line10431044 async def aiter_raw(self) -> typing.AsyncIterator[bytes]:1045 """1046 A byte-iterator over the raw response content.
3 unmodified lines
1050 if self.is_closed:1051 raise ResponseClosed()10521053 self.is_stream_consumed = True1011 with map_exceptions(HTTPCORE_EXC_MAP, request=self.request):1054 with map_exceptions(HTTPCORE_EXC_MAP, request=self._request):1055 async for part in self._raw_stream:1056 yield part1057 await self.aclose()1058
15 unmodified lines
1074 Automatically called if the response body is read to completion.1075 """1076 if not self.is_closed:1077 self.is_closed = True1078 if self._request is not None:1035 self._elapsed = self.request.timer.elapsed1079 self._elapsed = self.request.timer.elapsed1080 await self._raw_stream.aclose()108110821083class Cookies(MutableMapping):
178 unmodified lines
modified:tests/models/test_responses.py+77 added-1 removed
1import datetime2import json3from unittest import mock45import brotli6import pytest78import httpx9from httpx._content_streams import AsyncIteratorStream, IteratorStream
21 unmodified lines
31 assert response.elapsed >= datetime.timedelta(0)32 assert not response.is_error333435def test_raise_for_status():36 # 2xx status codes are not an error.37 response = httpx.Response(200, request=REQUEST)38 response.raise_for_status()3940 # 4xx status codes are a client error.41 response = httpx.Response(403, request=REQUEST)42 with pytest.raises(httpx.HTTPStatusError):43 response.raise_for_status()4445 # 5xx status codes are a server error.46 response = httpx.Response(500, request=REQUEST)47 with pytest.raises(httpx.HTTPStatusError):48 response.raise_for_status()4950 # Calling .raise_for_status without setting a request instance is51 # not valid. Should raise a runtime error.52 response = httpx.Response(200)53 with pytest.raises(RuntimeError):54 response.raise_for_status()555657def test_response_repr():58 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)59 assert repr(response) == "<Response [200 OK]>"60
333 unmodified lines
394 with mock.patch("httpx._models.guess_json_utf", return_value="utf-32"):395 response = httpx.Response(396 200, content=content, headers=headers, request=REQUEST397 )375 with pytest.raises(json.JSONDecodeError):398 with pytest.raises(json.decoder.JSONDecodeError):399 response.json()400401402def test_json_without_specified_encoding_value_error():403 data = {"greeting": "hello", "recipient": "world"}404 content = json.dumps(data).encode("utf-32-be")405 headers = {"Content-Type": "application/json"}406 # force incorrect guess from `guess_json_utf` to trigger error407 with mock.patch("httpx._models.guess_json_utf", return_value="utf-32"):408 response = httpx.Response(200, content=content, headers=headers)409 with pytest.raises(ValueError):410 response.json()411412413@pytest.mark.parametrize(414 "headers, expected",415 [416 (
11 unmodified lines
428)429def test_link_headers(headers, expected):430 response = httpx.Response(200, content=None, headers=headers, request=REQUEST)431 assert response.links == expected432433434@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))435def test_decode_error_with_request(header_value):436 headers = [(b"Content-Encoding", header_value)]437 body = b"test 123"438 compressed_body = brotli.compress(body)[3:]439 with pytest.raises(httpx.DecodingError):440 httpx.Response(200, headers=headers, content=compressed_body, request=REQUEST)441442443@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))444def test_value_error_without_request(header_value):445 headers = [(b"Content-Encoding", header_value)]446 body = b"test 123"447 compressed_body = brotli.compress(body)[3:]448 with pytest.raises(ValueError):449 httpx.Response(200, headers=headers, content=compressed_body)450451452def test_response_with_unset_request():453 response = httpx.Response(200, content=b"Hello, world!")454455 assert response.status_code == 200456 assert response.reason_phrase == "OK"457 assert response.text == "Hello, world!"458 assert not response.is_error459460461def test_set_request_after_init():462 response = httpx.Response(200, content=b"Hello, world!")463464 response.request = REQUEST465466 assert response.request == REQUEST467468469def test_cannot_access_unset_request():470 response = httpx.Response(200, content=b"Hello, world!")471472 with pytest.raises(RuntimeError):473 assert response.request is not None
modified:tests/test_decoders.py+5 added-7 removed
133 unmodified lines
134@pytest.mark.parametrize(135 "decoder", (BrotliDecoder, DeflateDecoder, GZipDecoder, IdentityDecoder)136)137def test_decoders_empty_cases(decoder):138 request = httpx.Request(method="GET", url="https://www.example.com")139 instance = decoder(request)140 assert instance.decode(b"") == b""138 response = httpx.Response(content=b"", status_code=200)139 instance = decoder()140 assert instance.decode(response.content) == b""141 assert instance.flush() == b""142143144@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))
61 unmodified lines
206 assert "".join(response.text) == "トラベル"207208209def test_text_decoder_empty_cases():210 request = httpx.Request(method="GET", url="https://www.example.com")211212 decoder = TextDecoder(request=request)210 decoder = TextDecoder()211 assert decoder.flush() == ""212215 decoder = TextDecoder(request=request)213 decoder = TextDecoder()214 assert decoder.decode(b"") == ""215 assert decoder.flush() == ""216217
75 unmodified lines