【发布时间】:2021-11-07 22:16:50
【问题描述】:
下面的代码旨在在 while 循环 中发送多个 HTTP 请求异步,并取决于每个请求的响应(请求“X”总是返回“XXX”,“Y”总是返回“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
【问题讨论】:
标签: python asynchronous python-asyncio coroutine