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
Provenance
- Commit
ec40d04- Tree
b37d32b- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
d15dc0b
5 files changed+31 added−31 removed
modified:docs/compatibility.md+4 added-4 removed
26 unmodified lines2728293031323334313233343536373831 unmodified lines26 unmodified lines```
Within a `stream()` block request data is made available with:
* `.stream_bytes()` - Instead of `response.iter_content()`* `.stream_text()` - Instead of `response.iter_content(decode_unicode=True)`* `.stream_lines()` - Instead of `response.iter_lines()`* `.stream_raw()` - Use this instead of `response.raw`* `.aiter_bytes()` - Instead of `response.iter_content()`* `.aiter_text()` - Instead of `response.iter_content(decode_unicode=True)`* `.aiter_lines()` - Instead of `response.iter_lines()`* `.aiter_raw()` - Use this instead of `response.raw`* `.read()` - Read the entire response body, making `request.text` and `response.content` available.
## SSL configuration
31 unmodified linesmodified:docs/quickstart.md+4 added-4 removed
302 unmodified lines303 You can stream the binary content of the response...304 305 ```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 ```310 311 Or the text of the response...312 313 ```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 ```318 319 Or stream the text, on a line-by-line basis...320 321 ```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 ```326 327 HTTPX will use universal line endings, normalising all cases to `\n`.1 unmodified line329 In 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.330 331 ```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 ```336 337 If 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 linesmodified:httpx/models.py+12 added-12 removed
917 unmodified lines918 """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._content924 925 @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_bytes932 933 @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_raw940 941- 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()952 953- 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()963 964- 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 line971 972- 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 linesmodified:tests/client/test_client.py+2 added-2 removed
69 unmodified lines70 body = b""71 72 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 += chunk76 77 assert response.status_code == 20078 assert body == b"Hello, world!"4 unmodified lines83 body = b""84 85 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 += chunk89 90 assert response.status_code == 20091 assert body == b"Hello, world!"103 unmodified linesmodified:tests/models/test_responses.py+9 added-9 removed
135 unmodified lines136 async def test_raw_interface():137 response = httpx.Response(200, content=b"Hello, world!")138 139 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!"143 144 145 @pytest.mark.asyncio146-async def test_stream_interface():146+async def test_bytes_interface():147 response = httpx.Response(200, content=b"Hello, world!")148 149 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!"153 154 155 @pytest.mark.asyncio156-async def test_stream_text():156+async def test_text_interface():157 response = httpx.Response(200, content=b"Hello, world!")158 159 await response.read()160 161 content = ""162- async for part in response.stream_text():162+ async for part in response.aiter_text():163 content += part164 assert content == "Hello, world!"165 166 167 @pytest.mark.asyncio168-async def test_stream_lines():168+async def test_lines_interface():169 response = httpx.Response(200, content=b"Hello,\nworld!")170 171 await response.read()172 173 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!"]177 178 3 unmodified lines182 183 await response.read()184 185 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!"189 190 15 unmodified lines206 async def test_cannot_read_after_stream_consumed():207 response = httpx.Response(200, content=async_streaming_body())208 209 content = b""210- async for part in response.stream_bytes():210+ async for part in response.aiter_bytes():211 content += part212 213 with pytest.raises(httpx.StreamConsumed):214 await response.read()73 unmodified lines