88import swibots
99from contextlib import suppress
1010from pathlib import Path
11+ from httpx import AsyncClient
1112from signal import signal as signal_fn , SIGINT , SIGTERM , SIGABRT
1213from io import BytesIO
1314from swibots .bots import Bot
@@ -273,19 +274,17 @@ async def handle_download(
273274 file_name : str ,
274275 directory = "downloads/" ,
275276 in_memory : bool = False ,
276- block : bool = True ,
277277 progress : DownloadProgressCallback = None ,
278278 progress_args : tuple = (),
279279 ):
280280 if directory is None or directory == "" :
281281 directory = "downloads/"
282282 if not in_memory :
283283 os .makedirs (directory , exist_ok = True )
284- temp_file_path = (
284+ file_path = (
285285 os .path .abspath (re .sub ("\\ \\ " , "/" , os .path .join (directory , file_name )))
286- + ".temp"
287286 )
288- file = BytesIO () if in_memory else open (temp_file_path , "wb" )
287+ file = BytesIO () if in_memory else open (file_path , "wb" )
289288
290289 d_progress = DownloadProgress (
291290 total = 0 ,
@@ -295,15 +294,13 @@ async def handle_download(
295294 url = url ,
296295 )
297296
298- if progress :
299- await progress (d_progress , * progress_args )
300297 try :
301- with httpx .stream ("GET" , url ) as response :
298+ async with AsyncClient () .stream ("GET" , url ) as response :
302299 d_progress .total = int (response .headers ["Content-Length" ])
303300 d_progress .downloaded = response .num_bytes_downloaded
304301 d_progress .client = response
305302 d_progress .started = True
306- for chunk in response .iter_bytes ():
303+ async for chunk in response .aiter_bytes ():
307304 file .write (chunk )
308305 d_progress .downloaded += len (chunk )
309306 if progress :
@@ -312,7 +309,7 @@ async def handle_download(
312309 except BaseException as e :
313310 if not in_memory :
314311 file .close ()
315- os .remove (temp_file_path )
312+ os .remove (file_path )
316313 if isinstance (e , CancelError ):
317314 return None
318315 if isinstance (e , asyncio .CancelledError ):
@@ -323,8 +320,6 @@ async def handle_download(
323320 return file
324321 else :
325322 file .close ()
326- file_path = os .path .splitext (temp_file_path )[0 ]
327- shutil .move (temp_file_path , file_path )
328323 return file_path
329324
330325 async def _on_app_stop (self ):
0 commit comments