mirror of
https://github.com/ClovertaTheTrilobita/SanYeCao-Nonebot.git
synced 2026-04-01 22:04:51 +00:00
- 将 requests 库替换为 aiohttp库,以支持异步请求- 重构 download_image 函数,使其支持异步下载
-优化图片下载逻辑,使用 while循环异步读取数据块
- 更新异常捕获类型,从 requests.RequestException 改为 aiohttp.ClientError
(cherry picked from commit c4b1019232)
21 lines
No EOL
647 B
Python
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}") |