VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > 简明python教程 >
  • Python协程&asyncio&异步编程(2)

def red(): # 异步操作接口 print("请求来了") await asyncio.sleep(3) # 连接池获取一个连接 conn = await REDIS_POOL.acquire() redis = Redis(conn) # 设置值 await redis.hmset_dict("car", key1=1, key2=2, key3=3) # 读取值 result = await redis.hgetall("car", encoding="utf-8") print(result) # 连接归还连接池 REDIS_POOL.release(conn) return result if __name__ == "__main__": uvicorn.run("mu:app", host="127.0.0.1", port=5000, log_level="info")

5.4爬虫

pip install aiohttp
import asyncio
import aiohttp


async def fetch(session, url):
    print("发送请求", url)
    async with session.get(url, verify_ssl=False) as response:
        text = await response.text()
        print("结果:", url, len(text))
        return text


async def main():
    async with aiohttp.ClientSession() as session:
        url_list = [
            "https://python.org",
            "https://www.baidu.com",
            "https://tianbaoo.github.io"
        ]

        tasks = [asyncio.create_task(fetch(session, url)) for url in url_list]
        done, pending = await asyncio.wait(tasks)
        print(done)

if __name__ == "__main__":
    asyncio.run(main())

6.总结

最大的意义:通过一个线程利用其IO等待时间去做其他事情。


相关教程