1200每分钟呼叫次数等于20每秒调用一次,这样您就可以将请求分成batches20 并在批次之间休眠一秒钟。
另一种选择是使用aiohttp.TCPConnector(limit=20)
对于客户端会话,但这仅限制了数量并发请求,因此您最终可能会执行更多请求(如果 API 响应速度快于一秒)或更少请求(如果 API 响应速度慢于一秒);看this https://stackoverflow.com/questions/61774125/aiohttp-set-number-of-requests-per-second相关问题。
批量示例:
# python 3.7+
import aiohttp
import asyncio
async def fetch(session, url):
data = None
async with session.get(url) as response:
if response.status != 200:
text = await response.text()
print("cannot retrieve %s: status: %d, reason: %s" % (url, response.status, text))
else :
data = await response.json()
return data
async def main(n):
print("starting")
session = aiohttp.ClientSession()
tasks = []
batch = []
for i in range(n):
batch.append("http://httpbin.org/anything?key=a%d" % i)
if len(batch) >= 20:
print("issuing batch %d:%d" % (i-20+1, i+1))
for url in batch:
task = asyncio.create_task(fetch(session, url))
tasks.append(task)
batch = []
await asyncio.sleep(1)
if batch: # if batch length does not divide n evenly consume last batch
print("issuing last batch %d:%d" % (n-len(batch), n))
for url in batch:
task = asyncio.create_task(fetch(session, url))
tasks.append(fetch(session, url))
responses = await asyncio.gather(*tasks, return_exceptions=True)
await session.close()
for response in responses:
assert "args" in response
# note that the responses will be in the order in which the requests were made
print("finished")
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main(111))
Output
starting
issuing batch 0:20
issuing batch 20:40
issuing batch 40:60
issuing batch 60:80
issuing batch 80:100
issuing last batch 100:111
finished
这里重要的一点是asyncio.create_task
(创建一个任务并启动它,返回一个任务对象),await asyncio.sleep(1)
(用于限制请求)和await asyncio.gather
(等待所有任务完成运行)。
对于 Python asyncio.ensure_future代替asyncio.create_task
.