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

标签 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))

最佳答案

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

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)

如果你修复了这个错误,你就会得到你想要的——所有的请求都会同时开始。

除非使用 Semaphore/Queue,否则您将对服务进行锤击。

无论如何,如果这是你想要的,你可以使用这个:

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))

感谢asyncio aiohttp progress bar with tqdm对于 tqdm :)

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

关于python - 如何使用 aiohttp 确定每秒请求数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42010693/

相关文章:

Python:执行脚本没有错误,不执行任何操作

python - 如何获取函数的名称作为字符串?

python - pd.read_excel ("file.xlsx")不会创建 'DataFrame' 而是 'OrderedDict'

c# - 在不返回 void、Task 或 Task<T> 的方法中等待某些内容的正确方法?

javascript - 异步与同步事件处理程序性能

python:如何输入字符串并将其用作查询匹配elasticsearch

Python:在三引号中键入制表符和\t 之间的区别

python - 从 Python webapp 保持与 mysql/mariadb 连接的最佳实践

python - 正确使用 asyncio.Condition 的 wait_for() 方法

C# await之后代码会继续执行吗?