mirror of
https://github.com/ClovertaTheTrilobita/SanYeCao-Nonebot.git
synced 2026-04-01 22:04:51 +00:00
refactor(src/clover_image): 使用 aiohttp 替代 requests 实现异步图片下载
- 将 requests 库替换为 aiohttp库,以支持异步请求- 重构 download_image 函数,使其支持异步下载 -优化图片下载逻辑,使用 while循环异步读取数据块 - 更新异常捕获类型,从 requests.RequestException 改为 aiohttp.ClientError
This commit is contained in:
parent
ed0f463a0f
commit
c4b1019232
1 changed files with 11 additions and 7 deletions
|
|
@ -1,4 +1,4 @@
|
||||||
import requests
|
import aiohttp
|
||||||
|
|
||||||
async def download_image(url,file_path):
|
async def download_image(url,file_path):
|
||||||
"""
|
"""
|
||||||
|
|
@ -8,10 +8,14 @@ async def download_image(url,file_path):
|
||||||
:return:
|
:return:
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
response = requests.get(url, stream=True)
|
async with aiohttp.ClientSession() as session:
|
||||||
response.raise_for_status()
|
async with session.get(url) as response:
|
||||||
with open(file_path, 'wb') as file:
|
response.raise_for_status()
|
||||||
for chunk in response.iter_content(chunk_size=8192):
|
with open(file_path, 'wb') as file:
|
||||||
file.write(chunk)
|
while True:
|
||||||
except requests.RequestException as e:
|
chunk = await response.content.read(8192)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
file.write(chunk)
|
||||||
|
except aiohttp.ClientError as e:
|
||||||
print(f"下载图片时出错: {e}")
|
print(f"下载图片时出错: {e}")
|
||||||
Loading…
Reference in a new issue