协程的11
在一个线程中 如果遇到IO等待时间,线程不会呆呆等着,利用空闲时间再去做其他任务
案例 下载三张图片
- 普通方式
# todo pip install requests
import requests
def download_to_mylocal(url):
print("开始下载", url)
# 发送网络请求,下载图片
response = requests.get(url)
print("下载完成", url)
file_name = url.split(".com")[-1].split(".jpg")[0].split("/")[-1]
with open(file_name+'.jpg', mode="wb") as file_object:
file_object.write(response.content)
if __name__ == "__main__":
url_list = [
"XX/31458PICm58PICKsqwrz9Ve8P_PIC2018.jpg!w1024_new_0",
"XX/31Y58PICHCQS58PIC4iKcGYNQ_PIC2018.jpg!w1024_new_small",
"XX/63H58PICAuF8vqJRcZ58PICMq_PIC2018.jpg!w1024_new_small"
]
for item in url_list:
download_to_mylocal(item)
- 协程方式(异步)
# todo 使用第三方模块 aiohttp
import aiohttp
import asyncio
async def fetch(session, url):
print("发送请求", url)
async with session.get(url, verify_ssl=False) as response:
content = await response.content.read()
file_name = url.split("/")[-1]
with open(file_name, mode='wb') as file_object:
file_object.write(content)
print("下载完成", url)
async def main():
async with aiohttp.ClientSession() as session:
url_list = [
"XXX/001345XOhx0.jpg",
"XXX/220208/200740-16443220602c60.jpg",
"XXX/234059-164381645989ad.jpg"
]
tasks = [asyncio.create_task(fetch(session, url)) for url in url_list]
await asyncio.wait(tasks)
if __name__ == "__main__":
asyncio.run(main())

浙公网安备 33010602011771号