异步http请求aiohttp模块演示

异步http请求aiohttp模块演示,第1张

#reuqests.get() 同步的代码 ->异步 *** 作aiohttp
#pip install aiohttp
import asyncio
import aiohttp
urls = {'网址'}

async def aiodownload(url):
    name = url.rsplit("/",1)[1]
#aiohttp.ClientSession() == reuqests
    async with aiohttp.ClientSession()as session: #requests
        async with session.get(url)as resp:#resp =requests.get()

             with open (name,'wb')as f:#创建文件  ##resp.content.read() 
                 f.write(await resp.content.read())#读取内容识异步的,需要await挂起
    print(name)

async def main():
    tasks = []
    for url in urls:
        tasks.append(aiodownload(url))
    await asyncio.wait(tasks)

#resp.content.read()== resp.content    #resp.text() == resp.text     #resp.json()=resp.json()

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/563749.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-03
下一篇 2022-04-03

发表评论

登录后才能评论

评论列表(0条)

保存