1
1
mirror of https://github.com/KenanZhu/AutoLibrary.git synced 2026-06-18 15:33:03 +08:00

fix(WebDriverDownloader): 优化下载速度计算逻辑并改用时间间隔触发回调

- 将回调触发条件由进度变化量改为固定时间间隔(0.5s), 避免突发数据导致速度虚高

- 修正 total_size == 0 为 total_size <= 0, 完善边界判断

- 重命名变量提升可读性(last_time/last_size -> last_callback_time/last_callback_size)
This commit is contained in:
2026-03-21 01:52:20 +08:00
parent 62c1ecdb07
commit 4924f4b031
+10 -13
View File
@@ -306,13 +306,12 @@ class WebDriverDownloader:
total_size = int(response.headers.get('Content-Length', 0)) total_size = int(response.headers.get('Content-Length', 0))
if response.status_code == 206: # Partial Content - server supports Range if response.status_code == 206: # Partial Content - server supports Range
total_size += downloaded_size total_size += downloaded_size
# download file with progress callback and speed calculation last_callback_time = time.time()
start_time = time.time() last_callback_size = downloaded_size
last_time = start_time callback_interval = 0.1
last_size = downloaded_size
last_progress = 0.0
with open(self.download_path, mode) as f: with open(self.download_path, mode) as f:
for chunk in response.iter_content(CHUNK_SIZE): for chunk in response.iter_content(CHUNK_SIZE):
current_time = time.time()
if cancel_event and cancel_event.is_set(): if cancel_event and cancel_event.is_set():
response.close() response.close()
return False return False
@@ -320,20 +319,18 @@ class WebDriverDownloader:
continue continue
f.write(chunk) f.write(chunk)
downloaded_size += len(chunk) downloaded_size += len(chunk)
if not progress_callback or total_size == 0: if not progress_callback or total_size <= 0:
continue continue
current_time = time.time()
current_progress = (downloaded_size/total_size)*98.0 current_progress = (downloaded_size/total_size)*98.0
if current_progress - last_progress >= 1.0 or current_progress == 98.0: if current_time - last_callback_time >= callback_interval or current_progress >= 98.0:
elapsed = current_time - last_time elapsed = current_time - last_callback_time
if elapsed > 0: if elapsed > 0:
speed = (downloaded_size - last_size)/elapsed/1024.0 # KB/s speed = (downloaded_size - last_callback_size)/(elapsed*1024.0)
else: else:
speed = 0.0 speed = 0.0
progress_callback(current_progress, 100, speed, "下载中...") progress_callback(current_progress, 100, speed, "下载中...")
last_progress = current_progress last_callback_time = current_time
last_size = downloaded_size last_callback_size = downloaded_size
last_time = current_time
if total_size > 0 and self.download_path.stat().st_size < total_size: if total_size > 0 and self.download_path.stat().st_size < total_size:
raise Exception(f"下载不完整 : {self.download_path.stat().st_size}/{total_size} 字节") raise Exception(f"下载不完整 : {self.download_path.stat().st_size}/{total_size} 字节")
return True return True