Python aiohttp设置每秒的请求数
我正在Flask中编写一个API,其中包含1000多个获取数据的请求,我想限制每秒的请求数。我试过:Python aiohttp设置每秒的请求数,python,asynchronous,flask-sqlalchemy,aiohttp,Python,Asynchronous,Flask Sqlalchemy,Aiohttp,我正在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
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)
如果我运行代码,在1s内我发送了超过200个请求。有没有办法限制请求?上述代码按预期工作(除了关于
标题未定义的小错误)
在我的机器上测试,httpbin
URL响应时间约为100ms,这意味着在并发度为20的情况下,它将在1秒内处理约200个请求(这也是您看到的):
100毫秒每个请求意味着10个请求在一秒钟内完成
每秒10个请求,并发度20表示每秒200个请求
limit选项(aiohttp.TCPConnector
)限制并发请求的数量,并且没有任何时间维度
要查看作用中的限制,请尝试使用更多值,如10
、20
、50
:
# 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
如果要使用每秒请求数
限制发送一批请求(例如20个),并使用asyncio.sleep(1.0)
暂停一秒钟,然后发送下一批请求,依此类推