并行调用API,每分钟有硬性限制。

问题描述 投票:2回答:1

我正试图对一个API进行并行调用。该API在停止之前有每分钟1200次调用的限制。 在低于限制的情况下,最有效的异步调用方式是什么?

def remove_html_tags(text):
    """Remove html tags from a string"""
    import re
    clean = re.compile('<.*?>')
    return re.sub(clean, ' ', text)

async def getRez(df, url):
async with aiohttp.ClientSession() as session:
        auth = aiohttp.BasicAuth('username',pwd)


        r = await session.get(url, auth=auth)


        if r.status == 200:
            content = await r.text()
            text = remove_html_tags(str(content))

        else:
            text = '500 Server Error'
        df.loc[df['url'] == url, ['RezText']] = [[text]]
        df['wordCount'] = df['RezText'].apply(lambda x: len(str(x).split(" ")))
        data = df[df["RezText"] != "500 Server Error"]


async def main(df):
    df['RezText'] = None
    await asyncio.gather(*[getRez(df, url) for url in df['url']])

loop = asyncio.get_event_loop()
loop.run_until_complete(main(data))
python async-await aiohttp
1个回答
1
投票

1200 每分钟通话量相当于 20 每秒调用一次,这样你就可以把你的请求分为 批次 的20,并在两批之间睡一秒钟。

另一个选择是使用 aiohttp.TCPConnector(limit=20) 但这只能限制客户会话的数量。并发申请所以你可能最终会做更多的请求(如果API响应快于一秒)或更少的请求(如果API响应慢于一秒);见 这个 相关问题。

批量示例。

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

输出

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 < 3.7,你可以使用 asyncio.ensure_future 而不是 asyncio.create_task.

© www.soinside.com 2019 - 2024. All rights reserved.