Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

python - speedup asyncio #61

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 14 additions & 13 deletions mkbsd.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ async def download_image(session, image_url, file_path):
except Exception as e:
print(f"Error downloading image: {str(e)}")

print(f"🖼️ Saved image to {file_path}")

async def main():
try:
async with aiohttp.ClientSession() as session:
Expand All @@ -29,7 +31,7 @@ async def main():
raise Exception(f"⛔ Failed to fetch JSON file: {response.status}")
json_data = await response.json()
data = json_data.get('data')

if not data:
raise Exception('⛔ JSON does not have a "data" property at its root.')

Expand All @@ -39,20 +41,19 @@ async def main():
print(f"📁 Created directory: {download_dir}")

file_index = 1
for key, subproperty in data.items():
if subproperty and subproperty.get('dhd'):
image_url = subproperty['dhd']
print(f"🔍 Found image URL!")
parsed_url = urlparse(image_url)
ext = os.path.splitext(parsed_url.path)[-1] or '.jpg'
filename = f"{file_index}{ext}"
file_path = os.path.join(download_dir, filename)
async with asyncio.TaskGroup() as group:
for key, subproperty in data.items():
if subproperty and subproperty.get('dhd'):
image_url = subproperty['dhd']
print(f"🔍 Found image URL!")
parsed_url = urlparse(image_url)
ext = os.path.splitext(parsed_url.path)[-1] or '.jpg'
filename = f"{file_index}{ext}"
file_path = os.path.join(download_dir, filename)

await download_image(session, image_url, file_path)
print(f"🖼️ Saved image to {file_path}")
group.create_task(download_image(session, image_url, file_path))

file_index += 1
await delay(250)
file_index += 1

except Exception as e:
print(f"Error: {str(e)}")
Expand Down