Advertisement
kopyl

Untitled

Dec 7th, 2023
566
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. dest_folder = "images/source-512/"
  2.  
  3.  
  4. async def download_file(session, icon_url_512, file_path, icon):
  5.     retry_count = 0
  6.     max_retries = 5
  7.     wait_seconds = 1
  8.  
  9.     while retry_count < max_retries:
  10.         try:
  11.             async with session.get(icon_url_512, timeout=1) as response:
  12.                 if response.status == 200:
  13.                     with open(file_path, "wb") as f:
  14.                         f.write(await response.read())
  15.                         db_icons.update_one({"_id": icon["_id"]}, {"$set": {"downloaded": True}})
  16.                     return
  17.                 else:
  18.                     print(f"Response status {response.status}. Retrying...")
  19.         except (aiohttp.ClientError, aiohttp.ServerTimeoutError) as e:
  20.             print(f"Caught an error: {e}. Retrying...")
  21.         except Exception as e:
  22.             print(f"An unexpected error occurred: {e}. Stopping retries.")
  23.             break
  24.  
  25.         retry_count += 1
  26.         await asyncio.sleep(wait_seconds)
  27.         wait_seconds *= 2
  28.  
  29.     print("Max retries reached. Could not download the file.")
  30.  
  31.  
  32. async def download_icon(icon, session):
  33.     file_name = icon["file_name"]
  34.     file_path = os.path.join(dest_folder, file_name)
  35.     icon_url = icon["url"]
  36.     icon_url_512 = icon_url.replace("/128/", "/512/")
  37.  
  38.     await download_file(session, icon_url_512, file_path, icon)
  39.  
  40.  
  41. async def download_all_icons():
  42.     skip = 0
  43.     async with aiohttp.ClientSession() as session:
  44.         while True:
  45.             tasks = []
  46.             for _ in range(100):
  47.                 icon = db_icons.find_one({"downloaded": False}, skip=skip)
  48.                 skip += 1
  49.                 if icon:
  50.                     task = asyncio.create_task(download_icon(icon, session))
  51.                     tasks.append(task)
  52.                 else:
  53.                     break
  54.            
  55.             await asyncio.gather(*tasks)
  56.  
  57.  
  58. await download_all_icons()
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement