Support `Response(content=<bytes iterator>)` (#1265)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Support Response(content=<bytes iterator>) * Update test for merged master
authored by Tom Christie · committed by GitHub · parent 4bd08be · Browse files · 6 files·+112 added−83 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+112 added−83 removed
- tests:+85 added−62 removed
- other:+27 added−21 removed
Provenance
- Commit
5ee6135- Tree
8d7840e- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
4bd08be
6 files changed+112 added−83 removed
modified:httpx/_content_streams.py+18 added-17 removed
6 unmodified lines7 8 import httpcore9 10 from ._exceptions import StreamConsumed11-from ._types import FileContent, FileTypes, RequestData, RequestFiles11+from ._types import FileContent, FileTypes, RequestData, RequestFiles, ResponseContent12 from ._utils import (13 format_form_param,14 guess_content_type,15 peek_filelike_length,55 unmodified lines71 """72 Request content encoded as plain bytes, using an byte iterator.73 """74 75- def __init__(76- self, iterator: typing.Iterator[bytes], close_func: typing.Callable = None77- ) -> None:75+ def __init__(self, iterator: typing.Iterator[bytes]) -> None:76 self.iterator = iterator79- self.close_func = close_func77 self.is_stream_consumed = False78 79 def can_replay(self) -> bool:80 return False10 unmodified lines91 92 def __aiter__(self) -> typing.AsyncIterator[bytes]:93 raise RuntimeError("Attempted to call a async iterator on an sync stream.")94 98- def close(self) -> None:99- if self.close_func is not None:100- self.close_func()95 102-96 class AsyncIteratorStream(ContentStream):97 """98 Request content encoded as plain bytes, using an async byte iterator.99 """100 108- def __init__(109- self, aiterator: typing.AsyncIterator[bytes], close_func: typing.Callable = None110- ) -> None:101+ def __init__(self, aiterator: typing.AsyncIterator[bytes]) -> None:102 self.aiterator = aiterator112- self.close_func = close_func103 self.is_stream_consumed = False104 105 def can_replay(self) -> bool:106 return False10 unmodified lines117 self.is_stream_consumed = True118 async for part in self.aiterator:119 yield part120 131- async def aclose(self) -> None:132- if self.close_func is not None:133- await self.close_func()121 135-122 class JSONStream(ContentStream):123 """124 Request content encoded as JSON.125 """261 unmodified lines387 data = typing.cast(typing.Iterator[bytes], data)388 return IteratorStream(iterator=data)389 390 raise TypeError(f"Unexpected type for 'data', {type(data)!r}")391+392+393+def encode_response(content: ResponseContent = None) -> ContentStream:394+ if content is None:395+ return ByteStream(b"")396+ elif isinstance(content, bytes):397+ return ByteStream(body=content)398+ elif hasattr(content, "__aiter__"):399+ content = typing.cast(typing.AsyncIterator[bytes], content)400+ return AsyncIteratorStream(aiterator=content)401+ elif hasattr(content, "__iter__"):402+ content = typing.cast(typing.Iterator[bytes], content)403+ return IteratorStream(iterator=content)404+405+ raise TypeError(f"Unexpected type for 'content', {type(content)!r}")modified:httpx/_models.py+7 added-4 removed
12 unmodified lines13 import chardet14 import rfc398615 import rfc3986.exceptions16 17-from ._content_streams import ByteStream, ContentStream, encode17+from ._content_streams import ByteStream, ContentStream, encode, encode_response18 from ._decoders import (19 SUPPORTED_DECODERS,20 ContentDecoder,21 IdentityDecoder,21 unmodified lines43 PrimitiveData,44 QueryParamTypes,45 RequestData,46 RequestFiles,47+ ResponseContent,48 URLTypes,49 )50 from ._utils import (51 flatten_queryparams,622 unmodified lines674 request: Request = None,675 http_version: str = None,676 headers: HeaderTypes = None,677 stream: ContentStream = None,677- content: bytes = None,678+ content: ResponseContent = None,679 history: typing.List["Response"] = None,680 elapsed_func: typing.Callable = None,681 ):682 self.status_code = status_code11 unmodified lines694 self.is_stream_consumed = False695 if stream is not None:696 self._raw_stream = stream697 else:697- self._raw_stream = ByteStream(body=content or b"")698- self.read()698+ self._raw_stream = encode_response(content)699+ if content is None or isinstance(content, bytes):700+ # Load the response body, except for streaming content.701+ self.read()702 703 self._num_bytes_downloaded = 0704 705 @property551 unmodified linesmodified:httpx/_types.py+2 added
61 unmodified lines62 "Auth",63 None,64 ]65 66+ResponseContent = Union[bytes, Iterator[bytes], AsyncIterator[bytes]]67+68 RequestData = Union[dict, str, bytes, Iterator[bytes], AsyncIterator[bytes]]69 70 FileContent = Union[IO[str], IO[bytes], str, bytes]71 FileTypes = Union[8 unmodified linesmodified:tests/models/test_responses.py+11 added-52 removed
3 unmodified lines4 import brotli5 import pytest6 7 import httpx8-from httpx._content_streams import AsyncIteratorStream, IteratorStream8 9 10 def streaming_body():11 yield b"Hello, "201 unmodified lines213 assert response.is_closed214 215 216 def test_iter_raw():218- stream = IteratorStream(iterator=streaming_body())217 response = httpx.Response(218 200,221- stream=stream,219+ content=streaming_body(),220 )221 222 raw = b""223 for part in response.iter_raw():1 unmodified line225 assert raw == b"Hello, world!"226 227 228 def test_iter_raw_increments_updates_counter():231- stream = IteratorStream(iterator=streaming_body())229+ response = httpx.Response(200, content=streaming_body())230 233- response = httpx.Response(234- 200,235- stream=stream,236- )237-231 num_downloaded = response.num_bytes_downloaded232 for part in response.iter_raw():233 assert len(part) == (response.num_bytes_downloaded - num_downloaded)234 num_downloaded = response.num_bytes_downloaded235 236 237 @pytest.mark.asyncio238 async def test_aiter_raw():246- stream = AsyncIteratorStream(aiterator=async_streaming_body())247- response = httpx.Response(248- 200,249- stream=stream,250- )239+ response = httpx.Response(200, content=async_streaming_body())240 241 raw = b""242 async for part in response.aiter_raw():243 raw += part1 unmodified line245 246 247 @pytest.mark.asyncio248 async def test_aiter_raw_increments_updates_counter():260- stream = AsyncIteratorStream(aiterator=async_streaming_body())249+ response = httpx.Response(200, content=async_streaming_body())250 262- response = httpx.Response(263- 200,264- stream=stream,265- )266-251 num_downloaded = response.num_bytes_downloaded252 async for part in response.aiter_raw():253 assert len(part) == (response.num_bytes_downloaded - num_downloaded)254 num_downloaded = response.num_bytes_downloaded74 unmodified lines329 assert content == ["Hello,\n", "world!"]330 331 332 def test_sync_streaming_response():349- stream = IteratorStream(iterator=streaming_body())333 response = httpx.Response(334 200,352- stream=stream,335+ content=streaming_body(),336 )337 338 assert response.status_code == 200339 assert not response.is_closed6 unmodified lines346 347 348 @pytest.mark.asyncio349 async def test_async_streaming_response():367- stream = AsyncIteratorStream(aiterator=async_streaming_body())350 response = httpx.Response(351 200,370- stream=stream,352+ content=async_streaming_body(),353 )354 355 assert response.status_code == 200356 assert not response.is_closed5 unmodified lines362 assert response.is_closed363 364 365 def test_cannot_read_after_stream_consumed():384- stream = IteratorStream(iterator=streaming_body())366 response = httpx.Response(367 200,387- stream=stream,368+ content=streaming_body(),369 )370 371 content = b""372 for part in response.iter_bytes():4 unmodified lines377 378 379 @pytest.mark.asyncio380 async def test_cannot_aread_after_stream_consumed():400- stream = AsyncIteratorStream(aiterator=async_streaming_body())381 response = httpx.Response(382 200,403- stream=stream,383+ content=async_streaming_body(),384 )385 386 content = b""387 async for part in response.aiter_bytes():3 unmodified lines391 await response.aread()392 393 394 def test_cannot_read_after_response_closed():415- is_closed = False416-417- def close_func():418- nonlocal is_closed419- is_closed = True420-421- stream = IteratorStream(iterator=streaming_body(), close_func=close_func)395 response = httpx.Response(396 200,424- stream=stream,397+ content=streaming_body(),398 )399 400 response.close()428- assert is_closed429-401 with pytest.raises(httpx.ResponseClosed):402 response.read()403 404 405 @pytest.mark.asyncio406 async def test_cannot_aread_after_response_closed():436- is_closed = False437-438- async def close_func():439- nonlocal is_closed440- is_closed = True441-442- stream = AsyncIteratorStream(443- aiterator=async_streaming_body(), close_func=close_func444- )407 response = httpx.Response(408 200,447- stream=stream,409+ content=async_streaming_body(),410 )411 412 await response.aclose()451- assert is_closed452-413 with pytest.raises(httpx.ResponseClosed):414 await response.aread()415 416 417 @pytest.mark.asyncio418 async def test_elapsed_not_available_until_closed():459- stream = AsyncIteratorStream(aiterator=async_streaming_body())419 response = httpx.Response(420 200,462- stream=stream,421+ content=async_streaming_body(),422 )423 424 with pytest.raises(RuntimeError):425 response.elapsed151 unmodified linesmodified:tests/test_content_streams.py+70 added-1 removed
1 unmodified line2 3 import pytest4 5 from httpx import StreamConsumed6-from httpx._content_streams import ContentStream, encode6+from httpx._content_streams import ContentStream, encode, encode_response7 8 9 @pytest.mark.asyncio10 async def test_base_content():239 unmodified lines250 b"<file content 2>\r\n",251 b"--+++--\r\n",252 ]253 )254+255+256+@pytest.mark.asyncio257+async def test_response_empty_content():258+ stream = encode_response()259+ sync_content = b"".join([part for part in stream])260+ async_content = b"".join([part async for part in stream])261+262+ assert stream.can_replay()263+ assert stream.get_headers() == {}264+ assert sync_content == b""265+ assert async_content == b""266+267+268+@pytest.mark.asyncio269+async def test_response_bytes_content():270+ stream = encode_response(content=b"Hello, world!")271+ sync_content = b"".join([part for part in stream])272+ async_content = b"".join([part async for part in stream])273+274+ assert stream.can_replay()275+ assert stream.get_headers() == {"Content-Length": "13"}276+ assert sync_content == b"Hello, world!"277+ assert async_content == b"Hello, world!"278+279+280+@pytest.mark.asyncio281+async def test_response_iterator_content():282+ def hello_world():283+ yield b"Hello, "284+ yield b"world!"285+286+ stream = encode_response(content=hello_world())287+ content = b"".join([part for part in stream])288+289+ assert not stream.can_replay()290+ assert stream.get_headers() == {"Transfer-Encoding": "chunked"}291+ assert content == b"Hello, world!"292+293+ with pytest.raises(RuntimeError):294+ [part async for part in stream]295+296+ with pytest.raises(StreamConsumed):297+ [part for part in stream]298+299+300+@pytest.mark.asyncio301+async def test_response_aiterator_content():302+ async def hello_world():303+ yield b"Hello, "304+ yield b"world!"305+306+ stream = encode_response(content=hello_world())307+ content = b"".join([part async for part in stream])308+309+ assert not stream.can_replay()310+ assert stream.get_headers() == {"Transfer-Encoding": "chunked"}311+ assert content == b"Hello, world!"312+313+ with pytest.raises(RuntimeError):314+ [part for part in stream]315+316+ with pytest.raises(StreamConsumed):317+ [part async for part in stream]318+319+320+def test_response_invalid_argument():321+ with pytest.raises(TypeError):322+ encode_response(123) # type: ignoremodified:tests/test_decoders.py+4 added-9 removed
2 unmodified lines3 import brotli4 import pytest5 6 import httpx7-from httpx._content_streams import AsyncIteratorStream7 from httpx._decoders import (8 BrotliDecoder,9 DeflateDecoder,10 GZipDecoder,117 unmodified lines128 yield compressor.compress(body)129 yield compressor.flush()130 131 headers = [(b"Content-Encoding", b"gzip")]133- stream = AsyncIteratorStream(aiterator=compress(body))132 response = httpx.Response(133 200,134 headers=headers,137- stream=stream,135+ content=compress(body),136 )137 assert not hasattr(response, "body")138 assert await response.aread() == body139 56 unmodified lines196 for chunk in data:197 yield chunk198 199 # Accessing `.text` on a read response.202- stream = AsyncIteratorStream(aiterator=iterator())200 response = httpx.Response(201 200,205- stream=stream,202+ content=iterator(),203 )204 await response.aread()205 assert response.text == (b"".join(data)).decode(encoding)206 207 # Streaming `.aiter_text` iteratively.211- stream = AsyncIteratorStream(aiterator=iterator())208 response = httpx.Response(209 200,214- stream=stream,210+ content=iterator(),211 )212 text = "".join([part async for part in response.aiter_text()])213 assert text == (b"".join(data)).decode(encoding)214 4 unmodified lines219 yield b"\x83g"220 yield b"\x83"221 yield b"\x89\x83x\x83\x8b"222 227- stream = AsyncIteratorStream(aiterator=iterator())223 response = httpx.Response(224 200,225 headers=[(b"Content-Type", b"text/html; charset=shift-jis")],231- stream=stream,226+ content=iterator(),227 )228 229 await response.aread()230 assert "".join(response.text) == "トラベル"90 unmodified lines