SanYeCao-Nonebot/src/clover_image/download_image.py
SlyAimer ef11f27d2b refactor(src/clover_image): 使用 aiohttp 替代 requests 实现异步图片下载
- 将 requests 库替换为 aiohttp库,以支持异步请求- 重构 download_image 函数,使其支持异步下载
-优化图片下载逻辑,使用 while循环异步读取数据块
- 更新异常捕获类型,从 requests.RequestException 改为 aiohttp.ClientError

(cherry picked from commit c4b1019232)
2025-03-12 21:39:54 +08:00

21 lines
No EOL
647 B
Python

import aiohttp
async def download_image(url,file_path):
"""
下载图片
:param url:
:param file_path:
:return:
"""
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
response.raise_for_status()
with open(file_path, 'wb') as file:
while True:
chunk = await response.content.read(8192)
if not chunk:
break
file.write(chunk)
except aiohttp.ClientError as e:
print(f"下载图片时出错: {e}")