Response.content
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by Tom Christie · parent dea4d42 · Browse files · 14 files·+130 added−92 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+130 added−92 removed
- tests:+63 added−55 removed
- other:+67 added−37 removed
Provenance
- Commit
4c55113- Tree
a0fe719- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
dea4d42
14 files changed+130 added−92 removed
modified:httpcore/dispatch/http11.py+1 added-1 removed
83 unmodified lines84 status_code=status_code,85 reason_phrase=reason_phrase,86 protocol="HTTP/1.1",87 headers=headers,88- body=body,88+ content=body,89 on_close=self.response_closed,90 request=request,91 )92 56 unmodified linesmodified:httpcore/dispatch/http2.py+1 added-1 removed
71 unmodified lines72 response = Response(73 status_code=status_code,74 protocol="HTTP/2",75 headers=headers,76- body=body,76+ content=body,77 on_close=on_close,78 request=request,79 )80 76 unmodified linesmodified:httpcore/__init__.py+1 added
12 unmodified lines13 ReadTimeout,14 RedirectBodyUnavailable,15 RedirectLoop,16 ResponseClosed,17+ ResponseNotRead,18 StreamConsumed,19 Timeout,20 TooManyRedirects,21 )7 unmodified linesmodified:httpcore/exceptions.py+10 added
76 unmodified lines77 been streamed.78 """79 80 81+class ResponseNotRead(Exception):82+ """83+ Attempted to access response content, without having called `read()`84+ after a streaming response.85+ """86+87+88 class ResponseClosed(Exception):89 """90 Attempted to read or stream response content, but the request has been91 closed without loading the body.5 unmodified lines97 Decoding of the response failed.98 """99 100 101+# Other cases...102+103+104 class InvalidURL(Exception):105 """106 URL was missing a hostname, or was not one of HTTP/HTTPS.107 """modified:httpcore/models.py+52 added-33 removed
7 unmodified lines8 Decoder,9 IdentityDecoder,10 MultiDecoder,11 )12-from .exceptions import ResponseClosed, StreamConsumed12+from .exceptions import ResponseClosed, ResponseNotRead, StreamConsumed13 from .status_codes import codes14 from .utils import get_reason_phrase, normalize_header_key, normalize_header_value15 16 URLTypes = typing.Union["URL", str]179 unmodified lines196 return self[key]197 except KeyError:198 return default199 200- def getlist(self, key: str, default: typing.Any = None, split_commas = None) -> typing.List[str]:200+ def getlist(201+ self, key: str, split_commas: bool=False202+ ) -> typing.List[str]:203 """204 Return multiple header values.205 206 If there are header values that include commas, then we default to2 unmodified lines209 See: https://tools.ietf.org/html/rfc7230#section-3.2.2210 """211 get_header_key = key.lower().encode(self.encoding)212 if split_commas is None:211- split_commas = get_header_key != b'set-cookie'213+ split_commas = get_header_key != b"set-cookie"214 215 values = [216 item_value.decode(self.encoding)217 for item_key, item_value in self._list218 if item_key == get_header_key219 ]220 219- if not values:220- return [] if default is None else default221-221 if not split_commas:222 return values223 224 split_values = []125 unmodified lines350 elif self.body:351 yield self.body352 353 def prepare(self) -> None:354+ """355+ Adds in any default headers. When using the `Client`, this will356+ end up being called into by the `prepare_request()` stage.357+358+ You can omit this behavior by calling `Client.send()` with an359+ explicitly built `Request` instance.360+ """361 auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]362 363 has_host = "host" in self.headers364 has_content_length = (23 unmodified lines388 *,389 reason_phrase: str = None,390 protocol: str = None,391 headers: HeaderTypes = None,386- body: BodyTypes = b"",392+ content: BodyTypes = b"",393 on_close: typing.Callable = None,394 request: Request = None,395 history: typing.List["Response"] = None,396 ):397 self.status_code = status_code392- if reason_phrase is None:393- self.reason_phrase = get_reason_phrase(status_code)398+ self.reason_phrase = reason_phrase or get_reason_phrase(status_code)394- else:395- self.reason_phrase = reason_phrase399 self.protocol = protocol400 self.headers = Headers(headers)398- self.on_close = on_close399- self.is_closed = False400- self.is_streamed = False401 402- if isinstance(body, bytes):402+ if isinstance(content, bytes):403 self.is_closed = True404- self.body = self.decoder.decode(body) + self.decoder.flush()404+ self.is_stream_consumed = True405+ self._raw_content = content406 else:406- self.body_aiter = body407+ self.is_closed = False408+ self.is_stream_consumed = False409+ self._raw_stream = content410 411+ self.on_close = on_close412 self.request = request413 self.history = [] if history is None else list(history)414 self.next = None # typing.Optional[typing.Callable]415 6 unmodified lines422 """423 return None if self.request is None else self.request.url424 425 @property426+ def content(self) -> bytes:427+ if not hasattr(self, "_content"):428+ if hasattr(self, "_raw_content"):429+ self._content = (430+ self.decoder.decode(self._raw_content) + self.decoder.flush()431+ )432+ else:433+ raise ResponseNotRead()434+ return self._content435+436+ @property437 def decoder(self) -> Decoder:438 """439 Returns a decoder instance which can be used to decode the raw byte440 content, depending on the Content-Encoding used in the response.441 """442 if not hasattr(self, "_decoder"):443 decoders = [] # type: typing.List[Decoder]429- values = self.headers.getlist("content-encoding", ["identity"])444+ values = self.headers.getlist("content-encoding", split_commas=True)445 for value in values:446 value = value.strip().lower()447 decoder_cls = SUPPORTED_DECODERS[value]448 decoders.append(decoder_cls())10 unmodified lines459 async def read(self) -> bytes:460 """461 Read and return the response content.462 """448- if not hasattr(self, "body"):449- body = b""463+ if not hasattr(self, "_content"):464+ content = b""465 async for part in self.stream():451- body += part452- self.body = body453- return self.body466+ content += part467+ self._content = content468+ return self._content469 470 async def stream(self) -> typing.AsyncIterator[bytes]:471 """472 A byte-iterator over the decoded response content.473 This allows us to handle gzip, deflate, and brotli encoded responses.474 """460- if hasattr(self, "body"):461- yield self.body475+ if hasattr(self, "_content"):476+ yield self._content477 else:478 async for chunk in self.raw():479 yield self.decoder.decode(chunk)480 yield self.decoder.flush()1 unmodified line482 async def raw(self) -> typing.AsyncIterator[bytes]:483 """484 A byte-iterator over the raw response content.485 """471- if self.is_streamed:472- raise StreamConsumed()473- if self.is_closed:474- raise ResponseClosed()475- self.is_streamed = True476- async for part in self.body_aiter:477- yield part478- await self.close()486+ if hasattr(self, "_raw_content"):487+ yield self._raw_content488+ else:489+ if self.is_stream_consumed:490+ raise StreamConsumed()491+ if self.is_closed:492+ raise ResponseClosed()493 494+ self.is_stream_consumed = True495+ async for part in self._raw_stream:496+ yield part497+ await self.close()498+499 async def close(self) -> None:500 """501 Close the response and release the connection.502 Automatically called if the response body is read to completion.19 unmodified linesmodified:httpcore/sync.py+2 added-2 removed
24 unmodified lines25 def headers(self) -> Headers:26 return self._response.headers27 28 @property29- def body(self) -> bytes:30- return self._response.body29+ def content(self) -> bytes:30+ return self._response.content31 32 def read(self) -> bytes:33 return self._loop.run_until_complete(self._response.read())34 49 unmodified linesmodified:tests/adapters/test_redirects.py+6 added-6 removed
64 unmodified lines65 66 elif request.url.path == "/cross_domain_target":67 headers = dict(request.headers.items())68 body = json.dumps({"headers": headers}).encode()69- return Response(codes.ok, body=body, request=request)69+ return Response(codes.ok, content=body, request=request)70 71 elif request.url.path == "/redirect_body":72 body = await request.read()73 headers = {"location": "/redirect_body_target"}1 unmodified line75 76 elif request.url.path == "/redirect_body_target":77 body = await request.read()78 body = json.dumps({"body": body.decode()}).encode()79- return Response(codes.ok, body=body, request=request)79+ return Response(codes.ok, content=body, request=request)80 81- return Response(codes.ok, body=b"Hello, world!", request=request)81+ return Response(codes.ok, content=b"Hello, world!", request=request)82 83 84 @pytest.mark.asyncio85 async def test_redirect_301():115 unmodified lines201 client = RedirectAdapter(MockDispatch())202 url = "https://example.com/cross_domain"203 headers = {"Authorization": "abc"}204 response = await client.request("GET", url, headers=headers)205- data = json.loads(response.body.decode())205+ data = json.loads(response.content.decode())206 assert response.url == URL("https://example.org/cross_domain_target")207 assert data == {"headers": {}}208 209 2 unmodified lines212 client = RedirectAdapter(MockDispatch())213 url = "https://example.org/cross_domain"214 headers = {"Authorization": "abc"}215 response = await client.request("GET", url, headers=headers)216- data = json.loads(response.body.decode())216+ data = json.loads(response.content.decode())217 assert response.url == URL("https://example.org/cross_domain_target")218 assert data == {"headers": {"authorization": "abc"}}219 220 2 unmodified lines223 client = RedirectAdapter(MockDispatch())224 url = "https://example.org/redirect_body"225 body = b"Example request body"226 response = await client.request("POST", url, body=body)227- data = json.loads(response.body.decode())227+ data = json.loads(response.content.decode())228 assert response.url == URL("https://example.org/redirect_body_target")229 assert data == {"body": "Example request body"}230 231 10 unmodified linesmodified:tests/dispatch/test_connections.py+1 added-1 removed
6 unmodified lines7 async def test_get(server):8 http = httpcore.HTTPConnection(origin="http://127.0.0.1:8000/")9 response = await http.request("GET", "http://127.0.0.1:8000/")10 assert response.status_code == 20011- assert response.body == b"Hello, world!"11+ assert response.content == b"Hello, world!"12 13 14 @pytest.mark.asyncio15 async def test_post(server):5 unmodified linesmodified:tests/dispatch/test_http2.py+5 added-5 removed
80 unmodified lines81 server = MockServer()82 async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:83 response = await conn.request("GET", "http://example.org")84 assert response.status_code == 20085- assert json.loads(response.body) == {"method": "GET", "path": "/", "body": ""}85+ assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}86 87 88 @pytest.mark.asyncio89 async def test_http2_post_request():90 server = MockServer()91 async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:92 response = await conn.request("POST", "http://example.org", body=b"<data>")93 assert response.status_code == 20094- assert json.loads(response.body) == {94+ assert json.loads(response.content) == {95 "method": "POST",96 "path": "/",97 "body": "<data>",98 }7 unmodified lines106 response_2 = await conn.request("GET", "http://example.org/2")107 response_3 = await conn.request("GET", "http://example.org/3")108 109 assert response_1.status_code == 200110- assert json.loads(response_1.body) == {"method": "GET", "path": "/1", "body": ""}110+ assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}111 112 assert response_2.status_code == 200113- assert json.loads(response_2.body) == {"method": "GET", "path": "/2", "body": ""}113+ assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}114 115 assert response_3.status_code == 200116- assert json.loads(response_3.body) == {"method": "GET", "path": "/3", "body": ""}116+ assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}modified:tests/models/test_headers.py+4 added-4 removed
145 unmodified lines146 def test_multiple_headers():147 """148 Most headers should split by commas for `getlist`, except 'Set-Cookie'.149 """150- h = httpcore.Headers([('set-cookie', 'a, b'), ('set-cookie', 'c')])151- h.getlist('Set-Cookie') == ['a, b', 'b']150+ h = httpcore.Headers([("set-cookie", "a, b"), ("set-cookie", "c")])151+ h.getlist("Set-Cookie") == ["a, b", "b"]152 153- h = httpcore.Headers([('vary', 'a, b'), ('vary', 'c')])154- h.getlist('Vary') == ['a', 'b', 'c']153+ h = httpcore.Headers([("vary", "a, b"), ("vary", "c")])154+ h.getlist("Vary") == ["a", "b", "c"]modified:tests/models/test_responses.py+15 added-16 removed
7 unmodified lines8 yield b"world!"9 10 11 def test_response():12- response = httpcore.Response(200, body=b"Hello, world!")12+ response = httpcore.Response(200, content=b"Hello, world!")13 assert response.status_code == 20014 assert response.reason_phrase == "OK"15- assert response.body == b"Hello, world!"15+ assert response.content == b"Hello, world!"16 assert response.is_closed17 18 19 @pytest.mark.asyncio20 async def test_read_response():21- response = httpcore.Response(200, body=b"Hello, world!")21+ response = httpcore.Response(200, content=b"Hello, world!")22 23 assert response.status_code == 20024- assert response.body == b"Hello, world!"24+ assert response.content == b"Hello, world!"25 assert response.is_closed26 27- body = await response.read()27+ content = await response.read()28 29- assert body == b"Hello, world!"30- assert response.body == b"Hello, world!"29+ assert content == b"Hello, world!"30+ assert response.content == b"Hello, world!"31 assert response.is_closed32 33 34 @pytest.mark.asyncio35 async def test_streaming_response():36- response = httpcore.Response(200, body=streaming_body())36+ response = httpcore.Response(200, content=streaming_body())37 38 assert response.status_code == 20039- assert not hasattr(response, "body")39 assert not response.is_closed40 42- body = await response.read()41+ content = await response.read()42 44- assert body == b"Hello, world!"45- assert response.body == b"Hello, world!"43+ assert content == b"Hello, world!"44+ assert response.content == b"Hello, world!"45 assert response.is_closed46 47 48 @pytest.mark.asyncio49 async def test_cannot_read_after_stream_consumed():51- response = httpcore.Response(200, body=streaming_body())50+ response = httpcore.Response(200, content=streaming_body())51 53- body = b""52+ content = b""53 async for part in response.stream():55- body += part54+ content += part55 56 with pytest.raises(httpcore.StreamConsumed):57 await response.read()58 59 60 @pytest.mark.asyncio61 async def test_cannot_read_after_response_closed():63- response = httpcore.Response(200, body=streaming_body())62+ response = httpcore.Response(200, content=streaming_body())63 64 await response.close()65 66 with pytest.raises(httpcore.ResponseClosed):7 unmodified linesmodified:tests/test_client.py+11 added-2 removed
7 unmodified lines8 url = "http://127.0.0.1:8000/"9 async with httpcore.Client() as client:10 response = await client.get(url)11 assert response.status_code == 20012- assert response.body == b"Hello, world!"12+ assert response.content == b"Hello, world!"13 14 15 @pytest.mark.asyncio16 async def test_post(server):7 unmodified lines24 async def test_stream_response(server):25 async with httpcore.Client() as client:26 response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)27 assert response.status_code == 20028- assert not hasattr(response, "body")28 body = await response.read()29 assert body == b"Hello, world!"30+ assert response.content == b"Hello, world!"31 32 33 @pytest.mark.asyncio34+async def test_access_content_stream_response(server):35+ async with httpcore.Client() as client:36+ response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)37+ assert response.status_code == 20038+ with pytest.raises(httpcore.ResponseNotRead):39+ response.content40+41+42+@pytest.mark.asyncio43 async def test_stream_request(server):44 async def hello_world():45 yield b"Hello, "46 yield b"world!"6 unmodified linesmodified:tests/test_decoders.py+15 added-14 removed
10 unmodified lines11 compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)12 compressed_body = compressor.compress(body) + compressor.flush()13 14 headers = [(b"Content-Encoding", b"deflate")]15- response = httpcore.Response(200, headers=headers, body=compressed_body)16- assert response.body == body15+ response = httpcore.Response(200, headers=headers, content=compressed_body)16+ assert response.content == body17 18 19 def test_gzip():20 body = b"test 123"21 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)22 compressed_body = compressor.compress(body) + compressor.flush()23 24 headers = [(b"Content-Encoding", b"gzip")]25- response = httpcore.Response(200, headers=headers, body=compressed_body)26- assert response.body == body25+ response = httpcore.Response(200, headers=headers, content=compressed_body)26+ assert response.content == body27 28 29 def test_brotli():30 body = b"test 123"31 compressed_body = brotli.compress(body)32 33 headers = [(b"Content-Encoding", b"br")]34- response = httpcore.Response(200, headers=headers, body=compressed_body)35- assert response.body == body34+ response = httpcore.Response(200, headers=headers, content=compressed_body)35+ assert response.content == body36 37 38 def test_multi():39 body = b"test 123"6 unmodified lines46 gzip_compressor.compress(compressed_body) + gzip_compressor.flush()47 )48 49 headers = [(b"Content-Encoding", b"deflate, gzip")]50- response = httpcore.Response(200, headers=headers, body=compressed_body)51- assert response.body == body50+ response = httpcore.Response(200, headers=headers, content=compressed_body)51+ assert response.content == body52 53 54 def test_multi_with_identity():55 body = b"test 123"56 compressed_body = brotli.compress(body)57 58 headers = [(b"Content-Encoding", b"br, identity")]59- response = httpcore.Response(200, headers=headers, body=compressed_body)60- assert response.body == body59+ response = httpcore.Response(200, headers=headers, content=compressed_body)60+ assert response.content == body61 62 headers = [(b"Content-Encoding", b"identity, br")]63- response = httpcore.Response(200, headers=headers, body=compressed_body)64- assert response.body == body63+ response = httpcore.Response(200, headers=headers, content=compressed_body)64+ assert response.content == body65 66 67 @pytest.mark.asyncio68 async def test_streaming():4 unmodified lines73 yield compressor.compress(body)74 yield compressor.flush()75 76 headers = [(b"Content-Encoding", b"gzip")]77- response = httpcore.Response(200, headers=headers, body=compress(body))77+ response = httpcore.Response(200, headers=headers, content=compress(body))78 assert not hasattr(response, "body")79 assert await response.read() == body80 81 2 unmodified lines84 headers = [(b"Content-Encoding", header_value)]85 body = b"test 123"86 compressed_body = brotli.compress(body)[3:]87 with pytest.raises(httpcore.exceptions.DecodingError):88- response = httpcore.Response(200, headers=headers, body=compressed_body)88+ response = httpcore.Response(200, headers=headers, content=compressed_body)89+ response.contentmodified:tests/test_sync.py+6 added-7 removed
26 unmodified lines27 def test_get(server):28 with httpcore.SyncConnectionPool() as http:29 response = http.request("GET", "http://127.0.0.1:8000/")30 assert response.status_code == 20031- assert response.body == b"Hello, world!"31+ assert response.content == b"Hello, world!"32 33 34 @threadpool35 def test_post(server):6 unmodified lines42 def test_stream_response(server):43 with httpcore.SyncConnectionPool() as http:44 response = http.request("GET", "http://127.0.0.1:8000/", stream=True)45 assert response.status_code == 20046- assert not hasattr(response, "body")47- body = response.read()48- assert body == b"Hello, world!"46+ content = response.read()47+ assert content == b"Hello, world!"48 49 50 @threadpool51 def test_stream_iterator(server):52 with httpcore.SyncConnectionPool() as http:53 response = http.request("GET", "http://127.0.0.1:8000/", stream=True)54 assert response.status_code == 20056- body = b""55+ content = b""56 for chunk in response.stream():58- body += chunk59- assert body == b"Hello, world!"57+ content += chunk58+ assert content == b"Hello, world!"