Sync streaming interface on responses (#695)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Sync streaming interface on responses * Fix test case * Test coverage for sync response APIs * Address review comments
authored by Tom Christie · committed by GitHub · parent b0bf2a7 · Browse files · 4 files·+352 added−80 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+352 added−80 removed
- tests:+194 added−43 removed
- other:+158 added−37 removed
Provenance
- Commit
11e7604- Tree
14e3c12- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
b0bf2a7
4 files changed+352 added−80 removed
modified:httpx/content_streams.py+64 added-2 removed
8 unmodified lines9 10 from .exceptions import StreamConsumed11 from .utils import format_form_param12 13-RequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]13+RequestData = typing.Union[14+ dict, str, bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]15+]16 17 RequestFiles = typing.Dict[18 str,19 typing.Union[28 unmodified lines48 body when we receive a redirect response.49 """50 return True51 52+ def __iter__(self) -> typing.Iterator[bytes]:53+ yield b""54+55+ def close(self) -> None:56+ pass57+58 async def __aiter__(self) -> typing.AsyncIterator[bytes]:59 yield b""60 61 async def aclose(self) -> None:13 unmodified lines75 return {}76 content_length = str(len(self.body))77 return {"Content-Length": content_length}78 79+ def __iter__(self) -> typing.Iterator[bytes]:80+ yield self.body81+82 async def __aiter__(self) -> typing.AsyncIterator[bytes]:83 yield self.body84 85 86+class IteratorStream(ContentStream):87+ """88+ Request content encoded as plain bytes, using an byte iterator.89+ """90+91+ def __init__(92+ self, iterator: typing.Iterator[bytes], close_func: typing.Callable = None93+ ) -> None:94+ self.iterator = iterator95+ self.close_func = close_func96+ self.is_stream_consumed = False97+98+ def can_replay(self) -> bool:99+ return False100+101+ def get_headers(self) -> typing.Dict[str, str]:102+ return {"Transfer-Encoding": "chunked"}103+104+ def __iter__(self) -> typing.Iterator[bytes]:105+ if self.is_stream_consumed:106+ raise StreamConsumed()107+ self.is_stream_consumed = True108+ for part in self.iterator:109+ yield part110+111+ def __aiter__(self) -> typing.AsyncIterator[bytes]:112+ raise RuntimeError("Attempted to call a async iterator on an sync stream.")113+114+ def close(self) -> None:115+ if self.close_func is not None:116+ self.close_func()117+118+119 class AsyncIteratorStream(ContentStream):120 """121 Request content encoded as plain bytes, using an async byte iterator.122 """10 unmodified lines133 134 def get_headers(self) -> typing.Dict[str, str]:135 return {"Transfer-Encoding": "chunked"}136 137+ def __iter__(self) -> typing.Iterator[bytes]:138+ raise RuntimeError("Attempted to call a sync iterator on an async stream.")139+140 async def __aiter__(self) -> typing.AsyncIterator[bytes]:141 if self.is_stream_consumed:142 raise StreamConsumed()143 self.is_stream_consumed = True17 unmodified lines161 content_length = str(len(self.body))162 content_type = "application/json"163 return {"Content-Length": content_length, "Content-Type": content_type}164 165+ def __iter__(self) -> typing.Iterator[bytes]:166+ yield self.body167+168 async def __aiter__(self) -> typing.AsyncIterator[bytes]:169 yield self.body170 171 9 unmodified lines181 content_length = str(len(self.body))182 content_type = "application/x-www-form-urlencoded"183 return {"Content-Length": content_length, "Content-Type": content_type}184 185+ def __iter__(self) -> typing.Iterator[bytes]:186+ yield self.body187+188 async def __aiter__(self) -> typing.AsyncIterator[bytes]:189 yield self.body190 191 112 unmodified lines304 content_length = str(len(self.body))305 content_type = self.content_type306 return {"Content-Length": content_length, "Content-Type": content_type}307 308+ def __iter__(self) -> typing.Iterator[bytes]:309+ yield self.body310+311 async def __aiter__(self) -> typing.AsyncIterator[bytes]:312 yield self.body313 314 20 unmodified lines335 else:336 return URLEncodedStream(data=data)337 elif isinstance(data, (str, bytes)):338 return ByteStream(body=data)283- else:339+ elif hasattr(data, "__aiter__"):340+ data = typing.cast(typing.AsyncIterator[bytes], data)341 return AsyncIteratorStream(aiterator=data)342+ elif hasattr(data, "__iter__"):343+ data = typing.cast(typing.Iterator[bytes], data)344+ return IteratorStream(iterator=data)345+346+ raise TypeError(f"Unexpected type for 'data', {type(data)!r}")modified:httpx/models.py+94 added-35 removed
11 unmodified lines12 import chardet13 import rfc398614 15 from .config import USER_AGENT16-from .content_streams import ContentStream, RequestData, RequestFiles, encode16+from .content_streams import (17+ ByteStream,18+ ContentStream,19+ RequestData,20+ RequestFiles,21+ encode,22+)23 from .decoders import (24 ACCEPT_ENCODING,25 SUPPORTED_DECODERS,26 Decoder,643 unmodified lines670 self.call_next: typing.Optional[typing.Callable] = None671 672 self.history = [] if history is None else list(history)673 668- if stream is None:669- self.is_closed = True670- self.is_stream_consumed = True671- self._raw_content = content or b""672- self._elapsed = request.timer.elapsed673- else:674- self.is_closed = False675- self.is_stream_consumed = False674+ self.is_closed = False675+ self.is_stream_consumed = False676+ if stream is not None:677 self._raw_stream = stream678+ else:679+ self._raw_stream = ByteStream(body=content or b"")680+ self.read()681 682 @property683 def elapsed(self) -> datetime.timedelta:684 """20 unmodified lines705 706 @property707 def content(self) -> bytes:708 if not hasattr(self, "_content"):705- if hasattr(self, "_raw_content"):706- raw_content = self._raw_content # type: ignore707- content = self.decoder.decode(raw_content)708- content += self.decoder.flush()709- self._content = content710- else:711- raise ResponseNotRead()709+ raise ResponseNotRead()710 return self._content711 712 @property713 def text(self) -> str:133 unmodified lines847 848 def __repr__(self) -> str:849 return f"<Response [{self.status_code} {self.reason_phrase}]>"850 853- async def aread(self) -> bytes:854- """855- Read and return the response content.856- """857- if not hasattr(self, "_content"):858- self._content = b"".join([part async for part in self.aiter_bytes()])859- return self._content860-851 @property852 def stream(self): # type: ignore853 warnings.warn( # pragma: nocover854 "Response.stream() is due to be deprecated. "8 unmodified lines863 "Use Response.aiter_raw() instead."864 )865 return self.aiter_raw # pragma: nocover866 867+ def read(self) -> bytes:868+ """869+ Read and return the response content.870+ """871+ if not hasattr(self, "_content"):872+ self._content = b"".join([part for part in self.iter_bytes()])873+ return self._content874+875+ def iter_bytes(self) -> typing.Iterator[bytes]:876+ """877+ A byte-iterator over the decoded response content.878+ This allows us to handle gzip, deflate, and brotli encoded responses.879+ """880+ if hasattr(self, "_content"):881+ yield self._content882+ else:883+ for chunk in self.iter_raw():884+ yield self.decoder.decode(chunk)885+ yield self.decoder.flush()886+887+ def iter_text(self) -> typing.Iterator[str]:888+ """889+ A str-iterator over the decoded response content890+ that handles both gzip, deflate, etc but also detects the content's891+ string encoding.892+ """893+ decoder = TextDecoder(encoding=self.charset_encoding)894+ for chunk in self.iter_bytes():895+ yield decoder.decode(chunk)896+ yield decoder.flush()897+898+ def iter_lines(self) -> typing.Iterator[str]:899+ decoder = LineDecoder()900+ for text in self.iter_text():901+ for line in decoder.decode(text):902+ yield line903+ for line in decoder.flush():904+ yield line905+906+ def iter_raw(self) -> typing.Iterator[bytes]:907+ """908+ A byte-iterator over the raw response content.909+ """910+ if self.is_stream_consumed:911+ raise StreamConsumed()912+ if self.is_closed:913+ raise ResponseClosed()914+915+ self.is_stream_consumed = True916+ for part in self._raw_stream:917+ yield part918+ self.close()919+920+ def close(self) -> None:921+ """922+ Close the response and release the connection.923+ Automatically called if the response body is read to completion.924+ """925+ if not self.is_closed:926+ self.is_closed = True927+ self._elapsed = self.request.timer.elapsed928+ if hasattr(self, "_raw_stream"):929+ self._raw_stream.close()930+931+ async def aread(self) -> bytes:932+ """933+ Read and return the response content.934+ """935+ if not hasattr(self, "_content"):936+ self._content = b"".join([part async for part in self.aiter_bytes()])937+ return self._content938+939 async def aiter_bytes(self) -> typing.AsyncIterator[bytes]:940 """941 A byte-iterator over the decoded response content.942 This allows us to handle gzip, deflate, and brotli encoded responses.27 unmodified lines970 async def aiter_raw(self) -> typing.AsyncIterator[bytes]:971 """972 A byte-iterator over the raw response content.973 """912- if hasattr(self, "_raw_content"):913- yield self._raw_content914- else:915- if self.is_stream_consumed:916- raise StreamConsumed()917- if self.is_closed:918- raise ResponseClosed()974+ if self.is_stream_consumed:975+ raise StreamConsumed()976+ if self.is_closed:977+ raise ResponseClosed()978 920- self.is_stream_consumed = True921- async for part in self._raw_stream:922- yield part923- await self.aclose()979+ self.is_stream_consumed = True980+ async for part in self._raw_stream:981+ yield part982+ await self.aclose()983 984 async def anext(self) -> "Response":985 """986 Get the next response from a redirect response.190 unmodified linesmodified:tests/models/test_responses.py+111 added-22 removed
3 unmodified lines4 5 import pytest6 7 import httpx8-from httpx.content_streams import AsyncIteratorStream8+from httpx.content_streams import AsyncIteratorStream, IteratorStream9 10 REQUEST = httpx.Request("GET", "https://example.org")11 12 110 unmodified lines123 assert response.text == "Snowman: â\x98\x83"124 assert response.encoding == "iso-8859-1"125 126 127+def test_read():128+ response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)129+130+ assert response.status_code == 200131+ assert response.text == "Hello, world!"132+ assert response.encoding == "ascii"133+ assert response.is_closed134+135+ content = response.read()136+137+ assert content == b"Hello, world!"138+ assert response.content == b"Hello, world!"139+ assert response.is_closed140+141+142 @pytest.mark.asyncio128-async def test_read_response():143+async def test_aread():144 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)145 146 assert response.status_code == 200147 assert response.text == "Hello, world!"6 unmodified lines154 assert response.content == b"Hello, world!"155 assert response.is_closed156 157 158+def test_iter_raw():159+ stream = IteratorStream(iterator=streaming_body())160+ response = httpx.Response(200, stream=stream, request=REQUEST)161+162+ raw = b""163+ for part in response.iter_raw():164+ raw += part165+ assert raw == b"Hello, world!"166+167+168 @pytest.mark.asyncio144-async def test_raw_interface():145- response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)169+async def test_aiter_raw():170+ stream = AsyncIteratorStream(aiterator=async_streaming_body())171+ response = httpx.Response(200, stream=stream, request=REQUEST)172 173 raw = b""174 async for part in response.aiter_raw():175 raw += part176 assert raw == b"Hello, world!"177 178 179+def test_iter_bytes():180+ response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)181+182+ content = b""183+ for part in response.iter_bytes():184+ content += part185+ assert content == b"Hello, world!"186+187+188 @pytest.mark.asyncio154-async def test_bytes_interface():189+async def test_aiter_bytes():190 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)191 192 content = b""193 async for part in response.aiter_bytes():194 content += part195 assert content == b"Hello, world!"196 197 163-@pytest.mark.asyncio164-async def test_text_interface():198+def test_iter_text():199 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)200 167- await response.aread()201+ content = ""202+ for part in response.iter_text():203+ content += part204+ assert content == "Hello, world!"205 206+207+@pytest.mark.asyncio208+async def test_aiter_text():209+ response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)210+211 content = ""212 async for part in response.aiter_text():213 content += part214 assert content == "Hello, world!"215 216 175-@pytest.mark.asyncio176-async def test_lines_interface():217+def test_iter_lines():218 response = httpx.Response(200, content=b"Hello,\nworld!", request=REQUEST)219 179- await response.aread()220+ content = []221+ for line in response.iter_lines():222+ content.append(line)223+ assert content == ["Hello,\n", "world!"]224 225+226+@pytest.mark.asyncio227+async def test_aiter_lines():228+ response = httpx.Response(200, content=b"Hello,\nworld!", request=REQUEST)229+230 content = []231 async for line in response.aiter_lines():232 content.append(line)233 assert content == ["Hello,\n", "world!"]234 235 187-@pytest.mark.asyncio188-async def test_stream_interface_after_read():189- response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)236+def test_sync_streaming_response():237+ stream = IteratorStream(iterator=streaming_body())238+ response = httpx.Response(200, stream=stream, request=REQUEST)239 191- await response.aread()240+ assert response.status_code == 200241+ assert not response.is_closed242 193- content = b""194- async for part in response.aiter_bytes():195- content += part243+ content = response.read()244+245 assert content == b"Hello, world!"246+ assert response.content == b"Hello, world!"247+ assert response.is_closed248 249 250 @pytest.mark.asyncio200-async def test_streaming_response():251+async def test_async_streaming_response():252 stream = AsyncIteratorStream(aiterator=async_streaming_body())253 response = httpx.Response(200, stream=stream, request=REQUEST)254 255 assert response.status_code == 2005 unmodified lines261 assert response.content == b"Hello, world!"262 assert response.is_closed263 264 265+def test_cannot_read_after_stream_consumed():266+ stream = IteratorStream(iterator=streaming_body())267+ response = httpx.Response(200, stream=stream, request=REQUEST)268+269+ content = b""270+ for part in response.iter_bytes():271+ content += part272+273+ with pytest.raises(httpx.StreamConsumed):274+ response.read()275+276+277 @pytest.mark.asyncio215-async def test_cannot_read_after_stream_consumed():278+async def test_cannot_aread_after_stream_consumed():279 stream = AsyncIteratorStream(aiterator=async_streaming_body())280 response = httpx.Response(200, stream=stream, request=REQUEST)281 282 content = b""3 unmodified lines286 with pytest.raises(httpx.StreamConsumed):287 await response.aread()288 289 290+def test_cannot_read_after_response_closed():291+ is_closed = False292+293+ def close_func():294+ nonlocal is_closed295+ is_closed = True296+297+ stream = IteratorStream(iterator=streaming_body(), close_func=close_func)298+ response = httpx.Response(200, stream=stream, request=REQUEST)299+300+ response.close()301+ assert is_closed302+303+ with pytest.raises(httpx.ResponseClosed):304+ response.read()305+306+307 @pytest.mark.asyncio228-async def test_cannot_read_after_response_closed():229- stream = AsyncIteratorStream(aiterator=async_streaming_body())308+async def test_cannot_aread_after_response_closed():309+ is_closed = False310+311+ async def close_func():312+ nonlocal is_closed313+ is_closed = True314+315+ stream = AsyncIteratorStream(316+ aiterator=async_streaming_body(), close_func=close_func317+ )318 response = httpx.Response(200, stream=stream, request=REQUEST)319 320 await response.aclose()321+ assert is_closed322 323 with pytest.raises(httpx.ResponseClosed):324 await response.aread()325 73 unmodified linesmodified:tests/test_content_streams.py+83 added-21 removed
1 import io2 3 import pytest4 5-from httpx.content_streams import encode5+from httpx.content_streams import ContentStream, encode6 from httpx.exceptions import StreamConsumed7 8 9 @pytest.mark.asyncio10+async def test_base_content():11+ stream = ContentStream()12+ sync_content = b"".join([part for part in stream])13+ async_content = b"".join([part async for part in stream])14+15+ assert stream.can_replay()16+ assert stream.get_headers() == {}17+ assert sync_content == b""18+ assert async_content == b""19+20+21+@pytest.mark.asyncio22 async def test_empty_content():23 stream = encode()12- content = b"".join([part async for part in stream])24+ sync_content = b"".join([part for part in stream])25+ async_content = b"".join([part async for part in stream])26 27 assert stream.can_replay()28 assert stream.get_headers() == {}16- assert content == b""29+ assert sync_content == b""30+ assert async_content == b""31 32 33 @pytest.mark.asyncio34 async def test_bytes_content():35 stream = encode(data=b"Hello, world!")22- content = b"".join([part async for part in stream])36+ sync_content = b"".join([part for part in stream])37+ async_content = b"".join([part async for part in stream])38 39 assert stream.can_replay()40 assert stream.get_headers() == {"Content-Length": "13"}26- assert content == b"Hello, world!"41+ assert sync_content == b"Hello, world!"42+ assert async_content == b"Hello, world!"43 44 45 @pytest.mark.asyncio30-async def test_aiterator_content():31- async def hello_world():46+async def test_iterator_content():47+ def hello_world():48 yield b"Hello, "49 yield b"world!"50 51 stream = encode(data=hello_world())36- content = b"".join([part async for part in stream])52+ content = b"".join([part for part in stream])53 54 assert not stream.can_replay()55 assert stream.get_headers() == {"Transfer-Encoding": "chunked"}56 assert content == b"Hello, world!"57 58+ with pytest.raises(RuntimeError):59+ [part async for part in stream]60 61+ with pytest.raises(StreamConsumed):62+ [part for part in stream]63+64+65 @pytest.mark.asyncio44-async def test_aiterator_is_stream_consumed():66+async def test_aiterator_content():67 async def hello_world():68 yield b"Hello, "69 yield b"world!"70 71 stream = encode(data=hello_world())50- b"".join([part async for part in stream])72+ content = b"".join([part async for part in stream])73 52- assert stream.is_stream_consumed74+ assert not stream.can_replay()75+ assert stream.get_headers() == {"Transfer-Encoding": "chunked"}76+ assert content == b"Hello, world!"77 54- with pytest.raises(StreamConsumed) as _:55- b"".join([part async for part in stream])78+ with pytest.raises(RuntimeError):79+ [part for part in stream]80 81+ with pytest.raises(StreamConsumed):82+ [part async for part in stream]83 84+85 @pytest.mark.asyncio86 async def test_json_content():87 stream = encode(json={"Hello": "world!"})61- content = b"".join([part async for part in stream])88+ sync_content = b"".join([part for part in stream])89+ async_content = b"".join([part async for part in stream])90 91 assert stream.can_replay()92 assert stream.get_headers() == {93 "Content-Length": "19",94 "Content-Type": "application/json",95 }68- assert content == b'{"Hello": "world!"}'96+ assert sync_content == b'{"Hello": "world!"}'97+ assert async_content == b'{"Hello": "world!"}'98 99 100 @pytest.mark.asyncio101 async def test_urlencoded_content():102 stream = encode(data={"Hello": "world!"})74- content = b"".join([part async for part in stream])103+ sync_content = b"".join([part for part in stream])104+ async_content = b"".join([part async for part in stream])105 106 assert stream.can_replay()107 assert stream.get_headers() == {108 "Content-Length": "14",109 "Content-Type": "application/x-www-form-urlencoded",110 }81- assert content == b"Hello=world%21"111+ assert sync_content == b"Hello=world%21"112+ assert async_content == b"Hello=world%21"113 114 115 @pytest.mark.asyncio116 async def test_multipart_files_content():117 files = {"file": io.BytesIO(b"<file content>")}118 stream = encode(files=files, boundary=b"+++")88- content = b"".join([part async for part in stream])119+ sync_content = b"".join([part for part in stream])120+ async_content = b"".join([part async for part in stream])121 122 assert stream.can_replay()123 assert stream.get_headers() == {124 "Content-Length": "138",125 "Content-Type": "multipart/form-data; boundary=+++",126 }95- assert content == b"".join(127+ assert sync_content == b"".join(128 [129 b"--+++\r\n",130 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',131 b"Content-Type: application/octet-stream\r\n",1 unmodified line133 b"<file content>\r\n",134 b"--+++--\r\n",135 ]136 )137+ assert async_content == b"".join(138+ [139+ b"--+++\r\n",140+ b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',141+ b"Content-Type: application/octet-stream\r\n",142+ b"\r\n",143+ b"<file content>\r\n",144+ b"--+++--\r\n",145+ ]146+ )147 148 149 @pytest.mark.asyncio150 async def test_multipart_data_and_files_content():151 data = {"message": "Hello, world!"}152 files = {"file": io.BytesIO(b"<file content>")}153 stream = encode(data=data, files=files, boundary=b"+++")112- content = b"".join([part async for part in stream])154+ sync_content = b"".join([part for part in stream])155+ async_content = b"".join([part async for part in stream])156 157 assert stream.can_replay()158 assert stream.get_headers() == {159 "Content-Length": "210",160 "Content-Type": "multipart/form-data; boundary=+++",161 }119- assert content == b"".join(162+ assert sync_content == b"".join(163 [164 b"--+++\r\n",165 b'Content-Disposition: form-data; name="message"\r\n',166 b"\r\n",5 unmodified lines172 b"<file content>\r\n",173 b"--+++--\r\n",174 ]175 )176+ assert async_content == b"".join(177+ [178+ b"--+++\r\n",179+ b'Content-Disposition: form-data; name="message"\r\n',180+ b"\r\n",181+ b"Hello, world!\r\n",182+ b"--+++\r\n",183+ b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',184+ b"Content-Type: application/octet-stream\r\n",185+ b"\r\n",186+ b"<file content>\r\n",187+ b"--+++--\r\n",188+ ]189+ )190+191+192+def test_invalid_argument():193+ with pytest.raises(TypeError):194+ encode(123)