python - 如果任务失败,如何调用 "task"?

标签 python python-3.x asynchronous async-await python-asyncio

make_request 函数向 API 发出 http 请求。而且我每秒不能发出超过 3 个请求。

我做过类似的事情

coroutines = [make_request(...) for ... in ...]
tasks = []
for coroutine in coroutines:
   tasks.append(asyncio.create_task(coroutine))
   await asyncio.sleep(1 / 3)
responses = asyncio.gather(*tasks)

但我每小时也不能发出超过 1000 个请求。 (可能,我可以延迟 3600/1000。)如果互联网连接丢失怎么办?我应该尝试再次提出请求。

我可以像这样包装make_request:

async def try_make_request(...):
   while True:
      try:
         return await make_request(...)
      exception APIError as err:
         logging.exception(...)

在这种情况下,每秒可能会发出超过 3 个请求。

我找到了 that解决方案,但我不确定这是最好的解决方案

pending = []
coroutines = [...]
for coroutine in coroutines:
    pending.append(asyncio.create_task(coroutine))
    await asyncio.sleep(1 / 3)
result = []
while True:
    finished, pending = await asyncio.wait(
        pending, return_when=asyncio.FIRST_EXCEPTION
    )
    for task in finished:
        exc = task.exception()
        if isinstance(exc, APIError) and exc.code == 29:
            pending.add(task.get_coro()) # since python 3.8
        if exc:
            logging.exception(...)
        else:
            result.append(task.result())
    if not pending:
        break

最佳答案

如果我对要求的理解正确,您发起连接的间隔不得超过 3.6 秒。实现这一目标的一种方法是设置一个计时器,每次启动连接时该计时器都会重置,并在 3.6 秒后到期,从而允许启动下一个连接。例如:

class Limiter:
    def __init__(self, delay):
        self.delay = delay
        self._ready = asyncio.Event()
        self._ready.set()

    async def wait(self):
        # wait in a loop because if there are multiple waiters,
        # the wakeup can be spurious
        while not self._ready.is_set():
            await self._ready.wait()
        # We got the slot and can proceed with the download.
        # Before doing so, clear the ready flag to prevent other waiters
        # from commencing downloads until the delay elapses again.
        self._ready.clear()
        asyncio.get_event_loop().call_later(self.delay, self._ready.set)

然后 try_make_request 可能如下所示:

async def try_make_request(limiter, ...):
    while True:
        await limiter.wait()
        try:
            return await make_request(...)
        exception APIError as err:
            logging.exception(...)

...主协程可以并行等待 try_make_request:

limiter = Limiter(3600/1000)
responses = await asyncio.gather(*[try_make_request(limiter, ...) for ... in ...])

关于python - 如果任务失败,如何调用 "task"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66518144/

相关文章:

python - 创建具有多个层次结构的嵌套字典,以 '.' 分隔

javascript - 在继续之前等待多个异步调用完成

node.js - 异步每个都会引入延迟

Python 类型提示 : when to use MutableSequence vs List

python - 在 Python 中使用多线程 blas 实现和多处理是否值得?

r - 从 R 调用 python 函数并传递参数

python - 将 float 组保存到图像(使用 EXR 格式)

windows - WaitForMultipleObjects() 是否重置所有自动重置事件?

python - 带有嵌入式 python 的程序无法使用 python 2.7.11 amd64 启动

python - 如何使用 Spacy 按句子分解文档