W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
如果需要監(jiān)視大型響應(yīng)的下載進度,可以使用響應(yīng)流式處理并檢查?response.num_bytes_downloaded
?屬性。
正確確定下載進度需要此接口,因為如果使用 HTTP 響應(yīng)壓縮,則返回的總字節(jié)數(shù)?response.content
?或?response.iter_content()
?并不總是與響應(yīng)的原始內(nèi)容長度相對應(yīng)。
注:下文的tqdm庫和rich庫都要使用pip進行安裝,可以使用 ?
pip install tqdm
? 來安裝tqdm庫,使用?pip install rich
? 來安裝rich庫
例如,在下載響應(yīng)時使用tqdm庫顯示進度條可以像這樣完成...
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)
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: