Skip to content
Myr

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

14 files+130 added−92 removed

modified:httpcore/dispatch/http11.py+1 added-1 removed
83 unmodified lines
84 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 lines
modified:httpcore/dispatch/http2.py+1 added-1 removed
71 unmodified lines
72 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 lines
modified:httpcore/__init__.py+1 added
12 unmodified lines
13 ReadTimeout,14 RedirectBodyUnavailable,15 RedirectLoop,16 ResponseClosed,17 ResponseNotRead,18 StreamConsumed,19 Timeout,20 TooManyRedirects,21)
7 unmodified lines
modified:httpcore/exceptions.py+10 added
76 unmodified lines
77 been streamed.78 """798081class ResponseNotRead(Exception):82 """83 Attempted to access response content, without having called `read()`84 after a streaming response.85 """868788class ResponseClosed(Exception):89 """90 Attempted to read or stream response content, but the request has been91 closed without loading the body.
5 unmodified lines
97 Decoding of the response failed.98 """99100101# Other cases...102103104class 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 lines
8 Decoder,9 IdentityDecoder,10 MultiDecoder,11)12from .exceptions import ResponseClosed, StreamConsumed12from .exceptions import ResponseClosed, ResponseNotRead, StreamConsumed13from .status_codes import codes14from .utils import get_reason_phrase, normalize_header_key, normalize_header_value1516URLTypes = typing.Union["URL", str]
179 unmodified lines
196 return self[key]197 except KeyError:198 return default199200 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.205206 If there are header values that include commas, then we default to
2 unmodified lines
209 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"214215 values = [216 item_value.decode(self.encoding)217 for item_key, item_value in self._list218 if item_key == get_header_key219 ]220219 if not values:220 return [] if default is None else default221221 if not split_commas:222 return values223224 split_values = []
125 unmodified lines
350 elif self.body:351 yield self.body352353 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.357358 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]]362363 has_host = "host" in self.headers364 has_content_length = (
23 unmodified lines
388 *,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 = False401402 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 = content410411 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 lines
422 """423 return None if self.request is None else self.request.url424425 @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._content435436 @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 lines
459 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._content469470 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 line
482 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()493494 self.is_stream_consumed = True495 async for part in self._raw_stream:496 yield part497 await self.close()498499 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 lines
modified:httpcore/sync.py+2 added-2 removed
24 unmodified lines
25 def headers(self) -> Headers:26 return self._response.headers2728 @property29 def body(self) -> bytes:30 return self._response.body29 def content(self) -> bytes:30 return self._response.content3132 def read(self) -> bytes:33 return self._loop.run_until_complete(self._response.read())34
49 unmodified lines
modified:tests/adapters/test_redirects.py+6 added-6 removed
64 unmodified lines
6566 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)7071 elif request.url.path == "/redirect_body":72 body = await request.read()73 headers = {"location": "/redirect_body_target"}
1 unmodified line
7576 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)8081 return Response(codes.ok, body=b"Hello, world!", request=request)81 return Response(codes.ok, content=b"Hello, world!", request=request)828384@pytest.mark.asyncio85async def test_redirect_301():
115 unmodified lines
201 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": {}}208209
2 unmodified lines
212 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"}}219220
2 unmodified lines
223 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"}230231
10 unmodified lines
modified:tests/dispatch/test_connections.py+1 added-1 removed
6 unmodified lines
7async 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!"121314@pytest.mark.asyncio15async def test_post(server):
5 unmodified lines
modified:tests/dispatch/test_http2.py+5 added-5 removed
80 unmodified lines
81 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": ""}868788@pytest.mark.asyncio89async 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 lines
106 response_2 = await conn.request("GET", "http://example.org/2")107 response_3 = await conn.request("GET", "http://example.org/3")108109 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": ""}111112 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": ""}114115 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 lines
146def 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"]152153 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 lines
8 yield b"world!"91011def 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_closed171819@pytest.mark.asyncio20async def test_read_response():21 response = httpcore.Response(200, body=b"Hello, world!")21 response = httpcore.Response(200, content=b"Hello, world!")2223 assert response.status_code == 20024 assert response.body == b"Hello, world!"24 assert response.content == b"Hello, world!"25 assert response.is_closed2627 body = await response.read()27 content = await response.read()2829 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_closed323334@pytest.mark.asyncio35async def test_streaming_response():36 response = httpcore.Response(200, body=streaming_body())36 response = httpcore.Response(200, content=streaming_body())3738 assert response.status_code == 20039 assert not hasattr(response, "body")39 assert not response.is_closed4042 body = await response.read()41 content = await response.read()4244 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_closed464748@pytest.mark.asyncio49async def test_cannot_read_after_stream_consumed():51 response = httpcore.Response(200, body=streaming_body())50 response = httpcore.Response(200, content=streaming_body())5153 body = b""52 content = b""53 async for part in response.stream():55 body += part54 content += part5556 with pytest.raises(httpcore.StreamConsumed):57 await response.read()585960@pytest.mark.asyncio61async def test_cannot_read_after_response_closed():63 response = httpcore.Response(200, body=streaming_body())62 response = httpcore.Response(200, content=streaming_body())6364 await response.close()6566 with pytest.raises(httpcore.ResponseClosed):
7 unmodified lines
modified:tests/test_client.py+11 added-2 removed
7 unmodified lines
8 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!"131415@pytest.mark.asyncio16async def test_post(server):
7 unmodified lines
24async 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!"313233@pytest.mark.asyncio34async 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.content404142@pytest.mark.asyncio43async def test_stream_request(server):44 async def hello_world():45 yield b"Hello, "46 yield b"world!"
6 unmodified lines
modified:tests/test_decoders.py+15 added-14 removed
10 unmodified lines
11 compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)12 compressed_body = compressor.compress(body) + compressor.flush()1314 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 == body171819def 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()2324 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 == body272829def test_brotli():30 body = b"test 123"31 compressed_body = brotli.compress(body)3233 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 == body363738def test_multi():39 body = b"test 123"
6 unmodified lines
46 gzip_compressor.compress(compressed_body) + gzip_compressor.flush()47 )4849 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 == body525354def test_multi_with_identity():55 body = b"test 123"56 compressed_body = brotli.compress(body)5758 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 == body6162 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 == body656667@pytest.mark.asyncio68async def test_streaming():
4 unmodified lines
73 yield compressor.compress(body)74 yield compressor.flush()7576 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() == body8081
2 unmodified lines
84 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.content
modified:tests/test_sync.py+6 added-7 removed
26 unmodified lines
27def 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!"323334@threadpool35def test_post(server):
6 unmodified lines
42def 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!"484950@threadpool51def 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!"