zoukankan      html  css  js  c++  java
  • aiohttp/asyncio 小例子和解释

    #!/usr/bin/env python  
    # encoding: utf-8  
    import aiohttp
    import asyncio
    import time
    # 通过async def定义的函数是原生的协程对象
    async  def fetch_async():
        conn=aiohttp.TCPConnector(verify_ssl=Flase)
        async with aiohttp.ClientSession(connector=conn) as session:
            async with session.get("http://www.baidu.com") as r:
               data=await r.text()   #和request的区别requests的方法是text,await就是协同的执行那些同步的任务,直到完成。
            return data[:10]
    
    
    start=time.time()
    #每个线程有一个事件循环,主线程调用asyncio.get_event_loop时会创建事件循环
    event_loop=asyncio.get_event_loop()
    tasks=[fetch_async() for i in range(10)]
    #run_until_complete方法,事件循环会安排协同程序的执行,asyncio.gather可以按顺序搜集异步任务执行的结果,
    results=event_loop.run_until_complete(asyncio.gather(*tasks))
    
    if __name__ == '__main__':
            for num,result in zip(list(range(10)),results):
                print(f'fetch({num}) = {result}')
    

      

  • 相关阅读:
    SpringBoot创建定时任务
    SpringBoot 多环境配置
    SpringBoot中使用log4j日志
    SpringBoot项目结构介绍
    SpringBoot快速入门
    Zookeeper Zkclient客户端
    Zookeeper java api
    学习微信小程序及知识占及v-if与v-show差别

    1像素
  • 原文地址:https://www.cnblogs.com/c-x-a/p/9077701.html
Copyright © 2011-2022 走看看