From ef11f27d2b69b49b999fb39d14a6feccf0d5c488 Mon Sep 17 00:00:00 2001 From: SlyAimer <2289782085@qq.com> Date: Wed, 12 Mar 2025 21:36:05 +0800 Subject: [PATCH] =?UTF-8?q?refactor(src/clover=5Fimage):=20=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=20aiohttp=20=E6=9B=BF=E4=BB=A3=20requests=20=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=E5=BC=82=E6=AD=A5=E5=9B=BE=E7=89=87=E4=B8=8B=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 将 requests 库替换为 aiohttp库,以支持异步请求- 重构 download_image 函数,使其支持异步下载 -优化图片下载逻辑,使用 while循环异步读取数据块 - 更新异常捕获类型,从 requests.RequestException 改为 aiohttp.ClientError (cherry picked from commit c4b10192323ebebb8827f3f06cac5d391fa9bab0) --- src/clover_image/download_image.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/clover_image/download_image.py b/src/clover_image/download_image.py index 3a8edb9..2eb2ca3 100644 --- a/src/clover_image/download_image.py +++ b/src/clover_image/download_image.py @@ -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}") \ No newline at end of file