refactor(src/clover_image): 使用 aiohttp 替代 requests 实现异步图片下载

- 将 requests 库替换为 aiohttp库,以支持异步请求- 重构 download_image 函数,使其支持异步下载
-优化图片下载逻辑,使用 while循环异步读取数据块
- 更新异常捕获类型,从 requests.RequestException 改为 aiohttp.ClientError

(cherry picked from commit c4b1019232)
This commit is contained in:
SlyAimer 2025-03-12 21:36:05 +08:00
parent f19eba1858
commit ef11f27d2b

View file

@ -1,4 +1,4 @@
import requests
import aiohttp
async def download_image(url,file_path):
"""
@ -8,10 +8,14 @@ async def download_image(url,file_path):
:return:
"""
try:
response = requests.get(url, stream=True)
response.raise_for_status()
with open(file_path, 'wb') as file:
for chunk in response.iter_content(chunk_size=8192):
file.write(chunk)
except requests.RequestException as e:
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}")