aiohttp 设置每秒请求数

aiohttp set number of requests per second

我在 Flask 中写了一个 API,有 1000 多个请求来获取数据,我想限制每秒的请求数。我试过:

conn = aiohttp.TCPConnector(limit_per_host=20)

and 

conn = aiohttp.TCPConnector(limit=20)

但是好像不行

我的代码如下所示:

import logging
import asyncio
import aiohttp

logging.basicConfig(filename="logfilename.log", level=logging.INFO, format='%(asctime)s %(levelname)s:%(message)s')


async def fetch(session, url):
    async with session.get(url, headers=headers) as response:
        if response.status == 200:
            data = await response.json()
            json = data['args']
        return json

async def fetch_all(urls, loop):
    conn = aiohttp.TCPConnector(limit=20)
    async with aiohttp.ClientSession(connector=conn, loop=loop) as session:
        results = await asyncio.gather(*[fetch(session, url) for url in urls], return_exceptions=True)
        return results

async def main():
    loop = asyncio.new_event_loop()
    url_list = []
    args = ['a', 'b', 'c', +1000 others]
    urls = url_list
    for i in args:
        base_url = 'http://httpbin.org/anything?key=%s' % i
        url_list.append(base_url)

    htmls = loop.run_until_complete(fetch_all(urls, loop))
    for j in htmls:
        key = j['key']
        # save to database
        logging.info(' %s was added', key)

如果我 运行 代码,我会在 1 秒内发送超过 200 个请求。有什么方法可以限制请求吗?

上面的代码按预期工作(除了关于 headers 未定义的小错误)。

在我的机器上测试 httpbin URL 在大约 100 毫秒内响应,这意味着并发数为 20 时它将在 1 秒内处理大约 200 个请求(这就是您所看到的嗯):

100 毫秒 每个请求意味着 10 个请求 在一秒内完成
10 个请求 每秒并发 20 表示一秒 200 个请求

限制选项(aiohttp.TCPConnector)限制并发请求数,没有任何时间维度。

要查看实际限制,请尝试使用更多值,例如 102050:

# time to complete 1000 requests with different keys
aiohttp.TCPConnector(limit=10): 12.58 seconds 
aiohttp.TCPConnector(limit=20): 6.57 seconds
aiohttp.TCPConnector(limit=50): 3.1 seconds

如果你想使用requests per second限制发送一批请求(例如20)并使用asyncio.sleep(1.0)暂停一秒钟,然后发送下一批,依此类推。