异步,While循环中的多个HTTP请求



下面的代码旨在在while循环中异步地发送多个HTTP请求,并根据每个请求的响应(request "X";总是返回"XXX", "总是返回"YYY"等等),做一些事情并为每个请求指定的interval秒睡眠


然而,它抛出一个错误…

RuntimeError: cannot reuse already awaited coroutine

有没有人可以帮助我如何修复代码以实现预期的行为?

class Client:
def __init__(self):
pass
async def run_forever(self, coro, interval):
while True:
res = await coro
await self._onresponse(res, interval)
async def _onresponse(self, res, interval):
if res == "XXX":
# ... do something with the resonse ...
await asyncio.sleep(interval)
if res == "YYY":
# ... do something with the resonse ...
await asyncio.sleep(interval)
if res == "ZZZ":
# ... do something with the resonse ...
await asyncio.sleep(interval)

async def request(something):
# ... HTTP request using aiohttp library ...
return response

async def main():
c = Client()
await c.run_forever(request("X"), interval=1)
await c.run_forever(request("Y"), interval=2)
await c.run_forever(request("Z"), interval=3)
# ... and more

正如错误提示所说,您不能等待一个协程多次。不是将协程传递给run_forever,然后在循环中等待它,而是传递协程的参数,并在每次循环迭代时等待一个新的协程。

class Client:
async def run_forever(self, value, interval):
while True:
res = await rqequest(value)
await self._response(response, interval)

您还需要改变等待run_forever的方式。await是阻塞的,所以当您用无限循环等待某个东西时,您永远不会到达下一行。相反,您希望一次收集多个协程。

async def main():
c = Client()
await asyncio.gather(
c.run_forever("X", interval=1),
c.run_forever("Y", interval=2),
c.run_forever("Z", interval=3),
)

最新更新