Skip to content
Myr

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

4 files+352 added−80 removed

modified:httpx/content_streams.py+64 added-2 removed
8 unmodified lines
910from .exceptions import StreamConsumed11from .utils import format_form_param1213RequestData = typing.Union[dict, str, bytes, typing.AsyncIterator[bytes]]13RequestData = typing.Union[14 dict, str, bytes, typing.Iterator[bytes], typing.AsyncIterator[bytes]15]1617RequestFiles = typing.Dict[18 str,19 typing.Union[
28 unmodified lines
48 body when we receive a redirect response.49 """50 return True5152 def __iter__(self) -> typing.Iterator[bytes]:53 yield b""5455 def close(self) -> None:56 pass5758 async def __aiter__(self) -> typing.AsyncIterator[bytes]:59 yield b""6061 async def aclose(self) -> None:
13 unmodified lines
75 return {}76 content_length = str(len(self.body))77 return {"Content-Length": content_length}7879 def __iter__(self) -> typing.Iterator[bytes]:80 yield self.body8182 async def __aiter__(self) -> typing.AsyncIterator[bytes]:83 yield self.body848586class IteratorStream(ContentStream):87 """88 Request content encoded as plain bytes, using an byte iterator.89 """9091 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 = False9798 def can_replay(self) -> bool:99 return False100101 def get_headers(self) -> typing.Dict[str, str]:102 return {"Transfer-Encoding": "chunked"}103104 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 part110111 def __aiter__(self) -> typing.AsyncIterator[bytes]:112 raise RuntimeError("Attempted to call a async iterator on an sync stream.")113114 def close(self) -> None:115 if self.close_func is not None:116 self.close_func()117118119class AsyncIteratorStream(ContentStream):120 """121 Request content encoded as plain bytes, using an async byte iterator.122 """
10 unmodified lines
133134 def get_headers(self) -> typing.Dict[str, str]:135 return {"Transfer-Encoding": "chunked"}136137 def __iter__(self) -> typing.Iterator[bytes]:138 raise RuntimeError("Attempted to call a sync iterator on an async stream.")139140 async def __aiter__(self) -> typing.AsyncIterator[bytes]:141 if self.is_stream_consumed:142 raise StreamConsumed()143 self.is_stream_consumed = True
17 unmodified lines
161 content_length = str(len(self.body))162 content_type = "application/json"163 return {"Content-Length": content_length, "Content-Type": content_type}164165 def __iter__(self) -> typing.Iterator[bytes]:166 yield self.body167168 async def __aiter__(self) -> typing.AsyncIterator[bytes]:169 yield self.body170171
9 unmodified lines
181 content_length = str(len(self.body))182 content_type = "application/x-www-form-urlencoded"183 return {"Content-Length": content_length, "Content-Type": content_type}184185 def __iter__(self) -> typing.Iterator[bytes]:186 yield self.body187188 async def __aiter__(self) -> typing.AsyncIterator[bytes]:189 yield self.body190191
112 unmodified lines
304 content_length = str(len(self.body))305 content_type = self.content_type306 return {"Content-Length": content_length, "Content-Type": content_type}307308 def __iter__(self) -> typing.Iterator[bytes]:309 yield self.body310311 async def __aiter__(self) -> typing.AsyncIterator[bytes]:312 yield self.body313314
20 unmodified lines
335 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)345346 raise TypeError(f"Unexpected type for 'data', {type(data)!r}")
modified:httpx/models.py+94 added-35 removed
11 unmodified lines
12import chardet13import rfc39861415from .config import USER_AGENT16from .content_streams import ContentStream, RequestData, RequestFiles, encode16from .content_streams import (17 ByteStream,18 ContentStream,19 RequestData,20 RequestFiles,21 encode,22)23from .decoders import (24 ACCEPT_ENCODING,25 SUPPORTED_DECODERS,26 Decoder,
643 unmodified lines
670 self.call_next: typing.Optional[typing.Callable] = None671672 self.history = [] if history is None else list(history)673668 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()681682 @property683 def elapsed(self) -> datetime.timedelta:684 """
20 unmodified lines
705706 @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._content711712 @property713 def text(self) -> str:
133 unmodified lines
847848 def __repr__(self) -> str:849 return f"<Response [{self.status_code} {self.reason_phrase}]>"850853 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._content860851 @property852 def stream(self): # type: ignore853 warnings.warn( # pragma: nocover854 "Response.stream() is due to be deprecated. "
8 unmodified lines
863 "Use Response.aiter_raw() instead."864 )865 return self.aiter_raw # pragma: nocover866867 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._content874875 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()886887 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()897898 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 line905906 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()914915 self.is_stream_consumed = True916 for part in self._raw_stream:917 yield part918 self.close()919920 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()930931 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._content938939 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 lines
970 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()978920 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()983984 async def anext(self) -> "Response":985 """986 Get the next response from a redirect response.
190 unmodified lines
modified:tests/models/test_responses.py+111 added-22 removed
3 unmodified lines
45import pytest67import httpx8from httpx.content_streams import AsyncIteratorStream8from httpx.content_streams import AsyncIteratorStream, IteratorStream910REQUEST = httpx.Request("GET", "https://example.org")1112
110 unmodified lines
123 assert response.text == "Snowman: â\x98\x83"124 assert response.encoding == "iso-8859-1"125126127def test_read():128 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)129130 assert response.status_code == 200131 assert response.text == "Hello, world!"132 assert response.encoding == "ascii"133 assert response.is_closed134135 content = response.read()136137 assert content == b"Hello, world!"138 assert response.content == b"Hello, world!"139 assert response.is_closed140141142@pytest.mark.asyncio128async def test_read_response():143async def test_aread():144 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)145146 assert response.status_code == 200147 assert response.text == "Hello, world!"
6 unmodified lines
154 assert response.content == b"Hello, world!"155 assert response.is_closed156157158def test_iter_raw():159 stream = IteratorStream(iterator=streaming_body())160 response = httpx.Response(200, stream=stream, request=REQUEST)161162 raw = b""163 for part in response.iter_raw():164 raw += part165 assert raw == b"Hello, world!"166167168@pytest.mark.asyncio144async def test_raw_interface():145 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)169async def test_aiter_raw():170 stream = AsyncIteratorStream(aiterator=async_streaming_body())171 response = httpx.Response(200, stream=stream, request=REQUEST)172173 raw = b""174 async for part in response.aiter_raw():175 raw += part176 assert raw == b"Hello, world!"177178179def test_iter_bytes():180 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)181182 content = b""183 for part in response.iter_bytes():184 content += part185 assert content == b"Hello, world!"186187188@pytest.mark.asyncio154async def test_bytes_interface():189async def test_aiter_bytes():190 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)191192 content = b""193 async for part in response.aiter_bytes():194 content += part195 assert content == b"Hello, world!"196197163@pytest.mark.asyncio164async def test_text_interface():198def test_iter_text():199 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)200167 await response.aread()201 content = ""202 for part in response.iter_text():203 content += part204 assert content == "Hello, world!"205206207@pytest.mark.asyncio208async def test_aiter_text():209 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)210211 content = ""212 async for part in response.aiter_text():213 content += part214 assert content == "Hello, world!"215216175@pytest.mark.asyncio176async def test_lines_interface():217def test_iter_lines():218 response = httpx.Response(200, content=b"Hello,\nworld!", request=REQUEST)219179 await response.aread()220 content = []221 for line in response.iter_lines():222 content.append(line)223 assert content == ["Hello,\n", "world!"]224225226@pytest.mark.asyncio227async def test_aiter_lines():228 response = httpx.Response(200, content=b"Hello,\nworld!", request=REQUEST)229230 content = []231 async for line in response.aiter_lines():232 content.append(line)233 assert content == ["Hello,\n", "world!"]234235187@pytest.mark.asyncio188async def test_stream_interface_after_read():189 response = httpx.Response(200, content=b"Hello, world!", request=REQUEST)236def test_sync_streaming_response():237 stream = IteratorStream(iterator=streaming_body())238 response = httpx.Response(200, stream=stream, request=REQUEST)239191 await response.aread()240 assert response.status_code == 200241 assert not response.is_closed242193 content = b""194 async for part in response.aiter_bytes():195 content += part243 content = response.read()244245 assert content == b"Hello, world!"246 assert response.content == b"Hello, world!"247 assert response.is_closed248249250@pytest.mark.asyncio200async def test_streaming_response():251async def test_async_streaming_response():252 stream = AsyncIteratorStream(aiterator=async_streaming_body())253 response = httpx.Response(200, stream=stream, request=REQUEST)254255 assert response.status_code == 200
5 unmodified lines
261 assert response.content == b"Hello, world!"262 assert response.is_closed263264265def test_cannot_read_after_stream_consumed():266 stream = IteratorStream(iterator=streaming_body())267 response = httpx.Response(200, stream=stream, request=REQUEST)268269 content = b""270 for part in response.iter_bytes():271 content += part272273 with pytest.raises(httpx.StreamConsumed):274 response.read()275276277@pytest.mark.asyncio215async def test_cannot_read_after_stream_consumed():278async def test_cannot_aread_after_stream_consumed():279 stream = AsyncIteratorStream(aiterator=async_streaming_body())280 response = httpx.Response(200, stream=stream, request=REQUEST)281282 content = b""
3 unmodified lines
286 with pytest.raises(httpx.StreamConsumed):287 await response.aread()288289290def test_cannot_read_after_response_closed():291 is_closed = False292293 def close_func():294 nonlocal is_closed295 is_closed = True296297 stream = IteratorStream(iterator=streaming_body(), close_func=close_func)298 response = httpx.Response(200, stream=stream, request=REQUEST)299300 response.close()301 assert is_closed302303 with pytest.raises(httpx.ResponseClosed):304 response.read()305306307@pytest.mark.asyncio228async def test_cannot_read_after_response_closed():229 stream = AsyncIteratorStream(aiterator=async_streaming_body())308async def test_cannot_aread_after_response_closed():309 is_closed = False310311 async def close_func():312 nonlocal is_closed313 is_closed = True314315 stream = AsyncIteratorStream(316 aiterator=async_streaming_body(), close_func=close_func317 )318 response = httpx.Response(200, stream=stream, request=REQUEST)319320 await response.aclose()321 assert is_closed322323 with pytest.raises(httpx.ResponseClosed):324 await response.aread()325
73 unmodified lines
modified:tests/test_content_streams.py+83 added-21 removed
1import io23import pytest45from httpx.content_streams import encode5from httpx.content_streams import ContentStream, encode6from httpx.exceptions import StreamConsumed789@pytest.mark.asyncio10async 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])1415 assert stream.can_replay()16 assert stream.get_headers() == {}17 assert sync_content == b""18 assert async_content == b""192021@pytest.mark.asyncio22async 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])2627 assert stream.can_replay()28 assert stream.get_headers() == {}16 assert content == b""29 assert sync_content == b""30 assert async_content == b""313233@pytest.mark.asyncio34async 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])3839 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!"434445@pytest.mark.asyncio30async def test_aiterator_content():31 async def hello_world():46async def test_iterator_content():47 def hello_world():48 yield b"Hello, "49 yield b"world!"5051 stream = encode(data=hello_world())36 content = b"".join([part async for part in stream])52 content = b"".join([part for part in stream])5354 assert not stream.can_replay()55 assert stream.get_headers() == {"Transfer-Encoding": "chunked"}56 assert content == b"Hello, world!"5758 with pytest.raises(RuntimeError):59 [part async for part in stream]6061 with pytest.raises(StreamConsumed):62 [part for part in stream]636465@pytest.mark.asyncio44async def test_aiterator_is_stream_consumed():66async def test_aiterator_content():67 async def hello_world():68 yield b"Hello, "69 yield b"world!"7071 stream = encode(data=hello_world())50 b"".join([part async for part in stream])72 content = b"".join([part async for part in stream])7352 assert stream.is_stream_consumed74 assert not stream.can_replay()75 assert stream.get_headers() == {"Transfer-Encoding": "chunked"}76 assert content == b"Hello, world!"7754 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]8081 with pytest.raises(StreamConsumed):82 [part async for part in stream]838485@pytest.mark.asyncio86async 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])9091 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!"}'9899100@pytest.mark.asyncio101async 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])105106 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"113114115@pytest.mark.asyncio116async 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])121122 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 line
133 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 )147148149@pytest.mark.asyncio150async 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])156157 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 lines
172 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 )190191192def test_invalid_argument():193 with pytest.raises(TypeError):194 encode(123)