如何使用aiohttp确定每秒的请求数?

时间:2017-02-02 19:25:29

标签: python python-3.x async-await python-asyncio aiohttp

我正在尝试使用aiohttp创建网络流量模拟器。以下代码示例异步生成10k个请求。我想知道它们中有多少是同时发生的,所以我可以说这个模型是10k用户同时请求网站。

如何确定并发网络请求的数量,或者如何确定aiohttp每秒发出的请求数?有没有办法实时调试/分析并发请求的数量?

有没有更好的方法来使用任何其他编程语言建模网络流量模拟器?

import asyncio
import aiohttp

async def fetch(session, url):
  with aiohttp.Timeout(10, loop=session.loop):
      async with session.get(url) as response:
            return await response.text()

async def run(r):
    url = "http://localhost:3000/"
    tasks = []

    # Create client session that will ensure we dont open new connection
    # per each request.
    async with aiohttp.ClientSession() as session:
        for i in range(r):
          html = await fetch(session, url)
          print(html)


# make 10k requests per second ?? (not confident this is true)
number = 10000
loop = asyncio.get_event_loop()
loop.run_until_complete(run(number))

1 个答案:

答案 0 :(得分:1)

首先,原始代码中有一个错误:

async with aiohttp.ClientSession() as session:
    for i in range(r):
      # This line (the await part) makes your code wait for a response
      # This means you done 1 concurent request
      html = await fetch(session, url)

如果您修复了错误,您将获得所需内容 - 所有请求都将同时启动。

除非使用信号量/队列,否则您将打破服务。

无论如何,如果您想要的话可​​以使用它:

import asyncio
import aiohttp
import tqdm


async def fetch(session, url):
    with aiohttp.Timeout(10, loop=session.loop):
        async with session.get(url) as response:
            return await response.text()


async def run(r):
    url = "http://localhost:3000/"
    tasks = []
    # The default connection is only 20 - you want to stress...
    conn = aiohttp.TCPConnector(limit=1000)
    tasks, responses = [], []
    async with aiohttp.ClientSession(connector=conn) as session:
        tasks = [asyncio.ensure_future(fetch(session, url)) for _ in range(r)]
        #This will show you some progress bar on the responses 
        for f in tqdm.tqdm(asyncio.as_completed(tasks), total=len(tasks)):
            responses.append(await f)
    return responses

number = 10000
loop = asyncio.get_event_loop()
loop.run_until_complete(run(number))

感谢tqdm的asyncio aiohttp progress bar with tqdm

我还建议阅读https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html以更好地理解协程如何工作。