Skip to content
Myr

Add aiter methods on response (#610)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tom Christie · committed by GitHub · parent d15dc0b · Browse files · 5 files+31 added−31 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+31 added−31 removed

  • tests:+11 added−11 removed
  • other:+20 added−20 removed

5 files+31 added−31 removed

modified:docs/compatibility.md+4 added-4 removed
modified:docs/quickstart.md+4 added-4 removed
302 unmodified lines
303You can stream the binary content of the response...304305```306>>> async with httpx.stream("GET", "https://www.example.com") as r:307... async for data in r.stream_bytes():307... async for data in r.aiter_bytes():308... print(data)309```310311Or the text of the response...312313```314>>> async with httpx.stream("GET", "https://www.example.com") as r:315... async for text in r.stream_text():315... async for text in r.aiter_text():316... print(text)317```318319Or stream the text, on a line-by-line basis...320321```322>>> async with httpx.stream("GET", "https://www.example.com") as r:323... async for line in r.stream_lines():323... async for line in r.aiter_lines():324... print(line)325```326327HTTPX will use universal line endings, normalising all cases to `\n`.
1 unmodified line
329In some cases you might want to access the raw bytes on the response without applying any HTTP content decoding. In this case any content encoding that the web server has applied such as `gzip`, `deflate`, or `brotli` will not be automatically decoded.330331```332>>> async with httpx.stream("GET", "https://www.example.com") as r:333... async for chunk in r.stream_raw():333... async for chunk in r.aiter_raw():334... print(chunk)335```336337If you're using streaming responses in any of these ways then the `response.content` and `response.text` attributes will not be available, and will raise errors if accessed. However you can also use the response streaming functionality to conditionally load the response body:
122 unmodified lines
modified:httpx/models.py+12 added-12 removed
917 unmodified lines
918 """919 Read and return the response content.920 """921 if not hasattr(self, "_content"):922 self._content = b"".join([part async for part in self.stream_bytes()])922 self._content = b"".join([part async for part in self.aiter_bytes()])923 return self._content924925 @property926 def stream(self): # type: ignore927 warnings.warn(928 "Response.stream() is due to be deprecated. "929 "Use Response.stream_bytes() instead."929 "Use Response.aiter_bytes() instead."930 )931 return self.stream_bytes931 return self.aiter_bytes932933 @property934 def raw(self): # type: ignore935 warnings.warn(936 "Response.raw() is due to be deprecated. "937 "Use Response.stream_raw() instead."937 "Use Response.aiter_raw() instead."938 )939 return self.stream_raw939 return self.aiter_raw940941 async def stream_bytes(self) -> typing.AsyncIterator[bytes]:941 async def aiter_bytes(self) -> typing.AsyncIterator[bytes]:942 """943 A byte-iterator over the decoded response content.944 This allows us to handle gzip, deflate, and brotli encoded responses.945 """946 if hasattr(self, "_content"):947 yield self._content948 else:949 async for chunk in self.stream_raw():949 async for chunk in self.aiter_raw():950 yield self.decoder.decode(chunk)951 yield self.decoder.flush()952953 async def stream_text(self) -> typing.AsyncIterator[str]:953 async def aiter_text(self) -> typing.AsyncIterator[str]:954 """955 A str-iterator over the decoded response content956 that handles both gzip, deflate, etc but also detects the content's957 string encoding.958 """959 decoder = TextDecoder(encoding=self.charset_encoding)960 async for chunk in self.stream_bytes():960 async for chunk in self.aiter_bytes():961 yield decoder.decode(chunk)962 yield decoder.flush()963964 async def stream_lines(self) -> typing.AsyncIterator[str]:964 async def aiter_lines(self) -> typing.AsyncIterator[str]:965 decoder = LineDecoder()966 async for text in self.stream_text():966 async for text in self.aiter_text():967 for line in decoder.decode(text):968 yield line969 for line in decoder.flush():970 yield line971972 async def stream_raw(self) -> typing.AsyncIterator[bytes]:972 async def aiter_raw(self) -> typing.AsyncIterator[bytes]:973 """974 A byte-iterator over the raw response content.975 """976 if hasattr(self, "_raw_content"):
205 unmodified lines
modified:tests/client/test_client.py+2 added-2 removed
69 unmodified lines
70 body = b""7172 async with httpx.Client() as client:73 async with client.stream("GET", server.url) as response:74 async for chunk in response.stream_bytes():74 async for chunk in response.aiter_bytes():75 body += chunk7677 assert response.status_code == 20078 assert body == b"Hello, world!"
4 unmodified lines
83 body = b""8485 async with httpx.Client() as client:86 async with client.stream("GET", server.url) as response:87 async for chunk in response.stream_raw():87 async for chunk in response.aiter_raw():88 body += chunk8990 assert response.status_code == 20091 assert body == b"Hello, world!"
103 unmodified lines
modified:tests/models/test_responses.py+9 added-9 removed
135 unmodified lines
136async def test_raw_interface():137 response = httpx.Response(200, content=b"Hello, world!")138139 raw = b""140 async for part in response.stream_raw():140 async for part in response.aiter_raw():141 raw += part142 assert raw == b"Hello, world!"143144145@pytest.mark.asyncio146async def test_stream_interface():146async def test_bytes_interface():147 response = httpx.Response(200, content=b"Hello, world!")148149 content = b""150 async for part in response.stream_bytes():150 async for part in response.aiter_bytes():151 content += part152 assert content == b"Hello, world!"153154155@pytest.mark.asyncio156async def test_stream_text():156async def test_text_interface():157 response = httpx.Response(200, content=b"Hello, world!")158159 await response.read()160161 content = ""162 async for part in response.stream_text():162 async for part in response.aiter_text():163 content += part164 assert content == "Hello, world!"165166167@pytest.mark.asyncio168async def test_stream_lines():168async def test_lines_interface():169 response = httpx.Response(200, content=b"Hello,\nworld!")170171 await response.read()172173 content = []174 async for line in response.stream_lines():174 async for line in response.aiter_lines():175 content.append(line)176 assert content == ["Hello,\n", "world!"]177178
3 unmodified lines
182183 await response.read()184185 content = b""186 async for part in response.stream_bytes():186 async for part in response.aiter_bytes():187 content += part188 assert content == b"Hello, world!"189190
15 unmodified lines
206async def test_cannot_read_after_stream_consumed():207 response = httpx.Response(200, content=async_streaming_body())208209 content = b""210 async for part in response.stream_bytes():210 async for part in response.aiter_bytes():211 content += part212213 with pytest.raises(httpx.StreamConsumed):214 await response.read()
73 unmodified lines