如果需要監(jiān)視大型響應(yīng)的下載進(jìn)度,可以使用響應(yīng)流式處理并檢查?response.num_bytes_downloaded
?屬性。
正確確定下載進(jìn)度需要此接口,因?yàn)槿绻褂?HTTP 響應(yīng)壓縮,則返回的總字節(jié)數(shù)?response.content
?或?response.iter_content()
?并不總是與響應(yīng)的原始內(nèi)容長度相對應(yīng)。
注:下文的tqdm庫和rich庫都要使用pip進(jìn)行安裝,可以使用 ?
pip install tqdm
? 來安裝tqdm庫,使用?pip install rich
? 來安裝rich庫
例如,在下載響應(yīng)時使用tqdm庫顯示進(jìn)度條可以像這樣完成...
import tempfile
import httpx
from tqdm import tqdm
with tempfile.NamedTemporaryFile() as download_file:
url = "https://speed.hetzner.de/100MB.bin"
with httpx.stream("GET", url) as response:
total = int(response.headers["Content-Length"])
with tqdm(total=total, unit_scale=True, unit_divisor=1024, unit="B") as progress:
num_bytes_downloaded = response.num_bytes_downloaded
for chunk in response.iter_bytes():
download_file.write(chunk)
progress.update(response.num_bytes_downloaded - num_bytes_downloaded)
num_bytes_downloaded = response.num_bytes_downloaded
或者另一個例子,這次使用rich庫...
import tempfile
import httpx
import rich.progress
with tempfile.NamedTemporaryFile() as download_file:
url = "https://speed.hetzner.de/100MB.bin"
with httpx.stream("GET", url) as response:
total = int(response.headers["Content-Length"])
with rich.progress.Progress(
"[progress.percentage]{task.percentage:>3.0f}%",
rich.progress.BarColumn(bar_width=None),
rich.progress.DownloadColumn(),
rich.progress.TransferSpeedColumn(),
) as progress:
download_task = progress.add_task("Download", total=total)
for chunk in response.iter_bytes():
download_file.write(chunk)
progress.update(download_task, completed=response.num_bytes_downloaded)
更多建議: