下面的代碼是為了在一個while回圈中異步發送多個HTTP請求,并根據每個請求的回應(請求 "X "總是回傳 "XXX","Y "總是回傳 "YYY",以此類推),做一些事情并sleep為每個請求指定interval秒。
然而,它拋出了一個錯誤......
RuntimeError: cannot reuse already awaited coroutine
誰能幫我修改一下代碼以實作預期的行為?
class Client。
def __init__(self):
pass: 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"/span>:
# ... do something with the resonse ....
await asyncio.sleep(interval)
if res == "YYY"/span>:
# ......對resonse做一些處理......。
await asyncio.sleep(interval)
if res == "ZZZ"/span>。
# ......對resonse做一些處理......。
await asyncio.sleep(interval)
async def request(something)。
# ... 使用aiohttp庫的HTTP請求 ...
return response
async def main()。
c = Client()
await c.run_forever(request("X"/span>), interval=1)
await c.run_forever(request("Y"/span>), interval=2)
await c.run_forever(request("Z"/span>), interval=3)
# ...還有更多。
uj5u.com熱心網友回復:
正如錯誤所說,你不能多次等待一個coroutine。與其將一個程式傳入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是阻塞的,所以當你用一個無限回圈來等待什么時,你將永遠不會到達下一行。相反,你想一次收集多個coroutines。
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) 。
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/318033.html
標籤:
