@@ -191,43 +191,35 @@ async def _stream_to_file(
191191 total_size : int ,
192192 start_time : float ,
193193 show_progress : bool ,
194- chunk_size : int = 8192 ,
195- flush_threshold : int = 256 * 1024 ,
196194) -> None :
197- """Stream HTTP response into file with buffered thread-offloaded writes."""
195+ """Stream HTTP response into file with thread-offloaded writes."""
198196 downloaded_size = 0
199- buffered = bytearray ()
200- progress_total = total_size if total_size > 0 else None
197+ known_total = total_size if total_size > 0 else None
201198
202199 while True :
203- chunk = await stream .read (chunk_size )
200+ chunk = await stream .read (8192 )
204201 if not chunk :
205202 break
206- buffered .extend (chunk )
203+ await asyncio .to_thread (file_obj .write , chunk )
204+
207205 downloaded_size += len (chunk )
206+ if show_progress :
207+ _print_download_progress (downloaded_size , known_total , start_time )
208208
209- if len (buffered ) >= flush_threshold :
210- chunk_to_write = bytes (buffered )
211- buffered .clear ()
212- await asyncio .to_thread (file_obj .write , chunk_to_write )
213209
214- if show_progress :
215- elapsed_time = max (time .time () - start_time , 1e-6 )
216- speed = downloaded_size / 1024 / elapsed_time # KB/s
217- if progress_total :
218- percent = downloaded_size / progress_total
219- print (
220- f"\r 下载进度: { percent :.2%} 速度: { speed :.2f} KB/s" ,
221- end = "" ,
222- )
223- else :
224- print (
225- f"\r 已下载: { downloaded_size } 字节 速度: { speed :.2f} KB/s" ,
226- end = "" ,
227- )
210+ def _print_download_progress (
211+ downloaded_size : int , total_size : int | None , start_time : float
212+ ) -> None :
213+ elapsed_time = max (time .time () - start_time , 1e-6 )
214+ speed = downloaded_size / 1024 / elapsed_time # KB/s
215+
216+ if total_size :
217+ percent = downloaded_size / total_size
218+ msg = f"\r 下载进度: { percent :.2%} 速度: { speed :.2f} KB/s"
219+ else :
220+ msg = f"\r 已下载: { downloaded_size } 字节 速度: { speed :.2f} KB/s"
228221
229- if buffered :
230- await asyncio .to_thread (file_obj .write , bytes (buffered ))
222+ print (msg , end = "" )
231223
232224
233225async def file_to_base64 (file_path : str ) -> str :
0 commit comments