python 之異步模塊 asyncio、aiohttp、gevent

  首先咱們要先理解異步請求,如下是示例代碼session

  import asyncio併發

  import time異步

  import aiohttpasync

  #定義第1個協程,協程就是將要具體完成的任務,該任務耗時3秒,完成後顯示任務完成oop

  async def to_do_something(i):url

  print('第{}個任務:任務啓動...'.format(i))spa

  #遇到耗時的操做,await就會使任務掛起,繼續去完成下一個任務orm

  await asyncio.sleep(i)協程

  print('第{}個任務:任務完成!'.format(i))ci

  #定義第2個協程,用於通知任務進行狀態

  async def mission_running():

  print('任務正在執行...')

  start = time.time()

  #建立一個循環

  loop = asyncio.get_event_loop()

  #建立一個任務盒子tasks,包含了3個須要完成的任務 , 建立task有兩種方法 第1種: loop.create_task(coroutine) 第二種: asyncio.ensure_future()

  tasks = [asyncio.ensure_future(to_do_something(5)),

  asyncio.ensure_future(to_do_something(2)),

  asyncio.ensure_future(to_do_something(8)),

  asyncio.ensure_future(mission_running())]

  #tasks接入loop中開始運行鄭州作人流多少錢 http://www.120zzzzyy.com/

  loop.run_until_complete(asyncio.wait(tasks))

  end = time.time()

  print(end-start)

  併發請求100次百度首頁只需1秒鐘

  import aiohttp

  import aiohttp, asyncio, time

  async def get(url):

  async with aiohttp.ClientSession() as session:

  async with session.get(url) as response:

  print(await response)

  async def request():

  url = 'http://www.baidu.com'

  resulit = await get(url)

  _now = lambda : time.time()

  start = _now()

  tasks = [asyncio.ensure_future(request()) for _ in range(100)]

  loop = asyncio.get_event_loop()

  loop.run_until_complete(asyncio.wait(tasks))

  print(_now()-start)

相關文章
相關標籤/搜索