httpx 監(jiān)視下載進(jìn)度

2022-07-21 11:40 更新

如果需要監(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)容長(zhǎng)度相對(duì)應(yīng)。

 注:下文的tqdm庫和rich庫都要使用pip進(jìn)行安裝,可以使用 ?pip install tqdm? 來安裝tqdm庫,使用? pip install rich? 來安裝rich庫

例如,在下載響應(yīng)時(shí)使用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

tqdm progress bar

或者另一個(gè)例子,這次使用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)

rich progress bar


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)