Skip to content
Myr

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

6 files+112 added−83 removed

modified:httpx/_content_streams.py+18 added-17 removed
6 unmodified lines
78import httpcore910from ._exceptions import StreamConsumed11from ._types import FileContent, FileTypes, RequestData, RequestFiles11from ._types import FileContent, FileTypes, RequestData, RequestFiles, ResponseContent12from ._utils import (13 format_form_param,14 guess_content_type,15 peek_filelike_length,
55 unmodified lines
71 """72 Request content encoded as plain bytes, using an byte iterator.73 """7475 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 = False7879 def can_replay(self) -> bool:80 return False
10 unmodified lines
9192 def __aiter__(self) -> typing.AsyncIterator[bytes]:93 raise RuntimeError("Attempted to call a async iterator on an sync stream.")9498 def close(self) -> None:99 if self.close_func is not None:100 self.close_func()9510296class AsyncIteratorStream(ContentStream):97 """98 Request content encoded as plain bytes, using an async byte iterator.99 """100108 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 = False104105 def can_replay(self) -> bool:106 return False
10 unmodified lines
117 self.is_stream_consumed = True118 async for part in self.aiterator:119 yield part120131 async def aclose(self) -> None:132 if self.close_func is not None:133 await self.close_func()121135122class JSONStream(ContentStream):123 """124 Request content encoded as JSON.125 """
261 unmodified lines
387 data = typing.cast(typing.Iterator[bytes], data)388 return IteratorStream(iterator=data)389390 raise TypeError(f"Unexpected type for 'data', {type(data)!r}")391392393def 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)404405 raise TypeError(f"Unexpected type for 'content', {type(content)!r}")
modified:httpx/_models.py+7 added-4 removed
12 unmodified lines
13import chardet14import rfc398615import rfc3986.exceptions1617from ._content_streams import ByteStream, ContentStream, encode17from ._content_streams import ByteStream, ContentStream, encode, encode_response18from ._decoders import (19 SUPPORTED_DECODERS,20 ContentDecoder,21 IdentityDecoder,
21 unmodified lines
43 PrimitiveData,44 QueryParamTypes,45 RequestData,46 RequestFiles,47 ResponseContent,48 URLTypes,49)50from ._utils import (51 flatten_queryparams,
622 unmodified lines
674 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_code
11 unmodified lines
694 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()702703 self._num_bytes_downloaded = 0704705 @property
551 unmodified lines
modified:httpx/_types.py+2 added
61 unmodified lines
62 "Auth",63 None,64]6566ResponseContent = Union[bytes, Iterator[bytes], AsyncIterator[bytes]]6768RequestData = Union[dict, str, bytes, Iterator[bytes], AsyncIterator[bytes]]6970FileContent = Union[IO[str], IO[bytes], str, bytes]71FileTypes = Union[
8 unmodified lines
modified:tests/models/test_responses.py+11 added-52 removed
3 unmodified lines
4import brotli5import pytest67import httpx8from httpx._content_streams import AsyncIteratorStream, IteratorStream8910def streaming_body():11 yield b"Hello, "
201 unmodified lines
213 assert response.is_closed214215216def test_iter_raw():218 stream = IteratorStream(iterator=streaming_body())217 response = httpx.Response(218 200,221 stream=stream,219 content=streaming_body(),220 )221222 raw = b""223 for part in response.iter_raw():
1 unmodified line
225 assert raw == b"Hello, world!"226227228def test_iter_raw_increments_updates_counter():231 stream = IteratorStream(iterator=streaming_body())229 response = httpx.Response(200, content=streaming_body())230233 response = httpx.Response(234 200,235 stream=stream,236 )237231 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_downloaded235236237@pytest.mark.asyncio238async 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())240241 raw = b""242 async for part in response.aiter_raw():243 raw += part
1 unmodified line
245246247@pytest.mark.asyncio248async def test_aiter_raw_increments_updates_counter():260 stream = AsyncIteratorStream(aiterator=async_streaming_body())249 response = httpx.Response(200, content=async_streaming_body())250262 response = httpx.Response(263 200,264 stream=stream,265 )266251 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_downloaded
74 unmodified lines
329 assert content == ["Hello,\n", "world!"]330331332def test_sync_streaming_response():349 stream = IteratorStream(iterator=streaming_body())333 response = httpx.Response(334 200,352 stream=stream,335 content=streaming_body(),336 )337338 assert response.status_code == 200339 assert not response.is_closed
6 unmodified lines
346347348@pytest.mark.asyncio349async 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 )354355 assert response.status_code == 200356 assert not response.is_closed
5 unmodified lines
362 assert response.is_closed363364365def 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 )370371 content = b""372 for part in response.iter_bytes():
4 unmodified lines
377378379@pytest.mark.asyncio380async 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 )385386 content = b""387 async for part in response.aiter_bytes():
3 unmodified lines
391 await response.aread()392393394def test_cannot_read_after_response_closed():415 is_closed = False416417 def close_func():418 nonlocal is_closed419 is_closed = True420421 stream = IteratorStream(iterator=streaming_body(), close_func=close_func)395 response = httpx.Response(396 200,424 stream=stream,397 content=streaming_body(),398 )399400 response.close()428 assert is_closed429401 with pytest.raises(httpx.ResponseClosed):402 response.read()403404405@pytest.mark.asyncio406async def test_cannot_aread_after_response_closed():436 is_closed = False437438 async def close_func():439 nonlocal is_closed440 is_closed = True441442 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 )411412 await response.aclose()451 assert is_closed452413 with pytest.raises(httpx.ResponseClosed):414 await response.aread()415416417@pytest.mark.asyncio418async 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 )423424 with pytest.raises(RuntimeError):425 response.elapsed
151 unmodified lines
modified:tests/test_content_streams.py+70 added-1 removed
1 unmodified line
23import pytest45from httpx import StreamConsumed6from httpx._content_streams import ContentStream, encode6from httpx._content_streams import ContentStream, encode, encode_response789@pytest.mark.asyncio10async def test_base_content():
239 unmodified lines
250 b"<file content 2>\r\n",251 b"--+++--\r\n",252 ]253 )254255256@pytest.mark.asyncio257async 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])261262 assert stream.can_replay()263 assert stream.get_headers() == {}264 assert sync_content == b""265 assert async_content == b""266267268@pytest.mark.asyncio269async 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])273274 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!"278279280@pytest.mark.asyncio281async def test_response_iterator_content():282 def hello_world():283 yield b"Hello, "284 yield b"world!"285286 stream = encode_response(content=hello_world())287 content = b"".join([part for part in stream])288289 assert not stream.can_replay()290 assert stream.get_headers() == {"Transfer-Encoding": "chunked"}291 assert content == b"Hello, world!"292293 with pytest.raises(RuntimeError):294 [part async for part in stream]295296 with pytest.raises(StreamConsumed):297 [part for part in stream]298299300@pytest.mark.asyncio301async def test_response_aiterator_content():302 async def hello_world():303 yield b"Hello, "304 yield b"world!"305306 stream = encode_response(content=hello_world())307 content = b"".join([part async for part in stream])308309 assert not stream.can_replay()310 assert stream.get_headers() == {"Transfer-Encoding": "chunked"}311 assert content == b"Hello, world!"312313 with pytest.raises(RuntimeError):314 [part for part in stream]315316 with pytest.raises(StreamConsumed):317 [part async for part in stream]318319320def test_response_invalid_argument():321 with pytest.raises(TypeError):322 encode_response(123) # type: ignore
modified:tests/test_decoders.py+4 added-9 removed
2 unmodified lines
3import brotli4import pytest56import httpx7from httpx._content_streams import AsyncIteratorStream7from httpx._decoders import (8 BrotliDecoder,9 DeflateDecoder,10 GZipDecoder,
117 unmodified lines
128 yield compressor.compress(body)129 yield compressor.flush()130131 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 lines
196 for chunk in data:197 yield chunk198199 # 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)206207 # 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 lines
219 yield b"\x83g"220 yield b"\x83"221 yield b"\x89\x83x\x83\x8b"222227 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 )228229 await response.aread()230 assert "".join(response.text) == "トラベル"
90 unmodified lines