Skip to content
Myr

Add progress to streaming download (#1268)

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

* Added last_raw_chunk_size to the Response object (#1208) * Added example with progress bar (#1208) Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Apply suggestions from code review Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * PR review Changed last_raw_chunk_size to num_bytes_downloaded ; Edited the example according to documentaion * Update docs/advanced.md Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Update docs/advanced.md Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Update docs/advanced.md * Update docs/advanced.md

authored by cdeler · committed by GitHub · parent 4d950e5 · Browse files · 3 files+67 added−0 removed
This commit

State

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

Trailers

  • Co-authored-by: Florimond Manca <florimond.manca@gmail.com>
  • Co-authored-by: Tom Christie <tom@tomchristie.com>

Diff stats

3 files+67 added−0 removed

  • tests:+29 added−0 removed
  • other:+38 added−0 removed

3 files+67 added−0 removed

modified:docs/advanced.md+28 added
219 unmodified lines
220 response = client.send(request)221 ...222```223224## Monitoring download progress225226If you need to monitor download progress of large responses, you can use response streaming and inspect the `response.num_bytes_downloaded` property.227228This interface is required for properly determining download progress, because the total number of bytes returned by `response.content` or `response.iter_content()` will not always correspond with the raw content length of the response if HTTP response compression is being used.229230For example, showing a progress bar using the [`tqdm`](https://github.com/tqdm/tqdm) library while a response is being downloaded could be done like this…231232```python233import tempfile234235import httpx236from tqdm import tqdm237238with tempfile.NamedTemporaryFile() as download_file:239 url = "https://speed.hetzner.de/100MB.bin"240 with httpx.stream("GET", url) as response:241 total = int(response.headers["Content-Length"])242243 with tqdm(total=total, unit_scale=True, unit_divisor=1024, unit="B") as progress:244 num_bytes_downloaded = response.num_bytes_downloaded245 for chunk in response.iter_bytes():246 download_file.write(chunk)247 progress.update(response.num_bytes_downloaded - num_bytes_downloaded)248 num_bytes_downloaded = response.num_bytes_downloaded249 print(f"The total download size is {response.num_bytes_downloaded} bytes")250```251252## .netrc Support253254HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter is255not defined, HTTPX tries to add auth into request's header from .netrc file.
725 unmodified lines
modified:httpx/_models.py+10 added
695 unmodified lines
696 else:697 self._raw_stream = ByteStream(body=content or b"")698 self.read()699700 self._num_bytes_downloaded = 0701702 @property703 def elapsed(self) -> datetime.timedelta:704 """705 Returns the time taken for the complete request/response
180 unmodified lines
886 key = link.get("rel") or link.get("url")887 ldict[key] = link888 return ldict889890 @property891 def num_bytes_downloaded(self) -> int:892 return self._num_bytes_downloaded893894 def __repr__(self) -> str:895 return f"<Response [{self.status_code} {self.reason_phrase}]>"896897 @contextlib.contextmanager
58 unmodified lines
956 if self.is_closed:957 raise ResponseClosed()958959 self.is_stream_consumed = True960 self._num_bytes_downloaded = 0961 with map_exceptions(HTTPCORE_EXC_MAP, request=self._request):962 for part in self._raw_stream:963 self._num_bytes_downloaded += len(part)964 yield part965 self.close()966967 def next(self) -> "Response":
71 unmodified lines
1039 if self.is_closed:1040 raise ResponseClosed()10411042 self.is_stream_consumed = True1043 self._num_bytes_downloaded = 01044 with map_exceptions(HTTPCORE_EXC_MAP, request=self._request):1045 async for part in self._raw_stream:1046 self._num_bytes_downloaded += len(part)1047 yield part1048 await self.aclose()10491050 async def anext(self) -> "Response":
202 unmodified lines
modified:tests/models/test_responses.py+29 added
225 unmodified lines
226 raw += part227 assert raw == b"Hello, world!"228229230def test_iter_raw_increments_updates_counter():231 stream = IteratorStream(iterator=streaming_body())232233 response = httpx.Response(234 200,235 stream=stream,236 )237238 num_downloaded = response.num_bytes_downloaded239 for part in response.iter_raw():240 assert len(part) == (response.num_bytes_downloaded - num_downloaded)241 num_downloaded = response.num_bytes_downloaded242243244@pytest.mark.asyncio245async def test_aiter_raw():246 stream = AsyncIteratorStream(aiterator=async_streaming_body())247 response = httpx.Response(
6 unmodified lines
254 raw += part255 assert raw == b"Hello, world!"256257258@pytest.mark.asyncio259async def test_aiter_raw_increments_updates_counter():260 stream = AsyncIteratorStream(aiterator=async_streaming_body())261262 response = httpx.Response(263 200,264 stream=stream,265 )266267 num_downloaded = response.num_bytes_downloaded268 async for part in response.aiter_raw():269 assert len(part) == (response.num_bytes_downloaded - num_downloaded)270 num_downloaded = response.num_bytes_downloaded271272273def test_iter_bytes():274 response = httpx.Response(275 200,276 content=b"Hello, world!",
341 unmodified lines