python 之异步模块 asyncio、aiohttp、gevent

  首先我们要先理解异步请求,以下是示例代码

  import asyncio

  import time

  import aiohttp

  #定义第1个协程,协程就是将要具体完成的任务,该任务耗时3秒,完成后显示任务完成

  async def to_do_something(i):

  print('第{}个任务:任务启动...'.format(i))

  #遇到耗时的操作,await就会使任务挂起,继续去完成下一个任务

  await asyncio.sleep(i)

  print('第{}个任务:任务完成!'.format(i))

  #定义第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)

posted @ 2019-12-11 15:13  网管布吉岛  阅读(803)  评论(0编辑  收藏  举报