【发布时间】:2021-06-23 01:55:02
【问题描述】:
我正在开发一个程序,它异步向一个服务发送一堆请求。从现在开始我就有了一部分,那里只是请求并等待结果(ok_function)。现在我需要添加获得结果的部分,如果是 202 等待一段时间再试一次,因为它返回 200。
看起来像这样:
async def async_make_requests(parsed_data, url):
async with aiohttp.ClientSession() as session:
tasks = []
for x, y in parsed_data.items():
if something:
tasks.append(
asyncio.ensure_future(
function_with_sleep(
session, x, y,
)
)
)
else:
tasks.append(
asyncio.ensure_future(
ok_function(
session, x, y,
)
)
)
results = await asyncio.gather(*tasks)
return results
async def function_with_sleep(session, x, y):
not_processed_yet = True
while not_processed_yet:
async with session.get(x, data=y) as r:
response = await r.json()
status_code = r.status
if status_code == 202:
await asyncio.sleep(10)
else:
not_processed_yet = False
...
async def ok_function(session, x, y)
async with session.post(x, data=y) as r:
response = await r.json()
status_code = r.status
...
在测试时:
resp_processing = MockResponse(202, response)
resp_ok = MockResponse(200, response)
mocker.patch("aiohttp.ClientSession.get", side_effect=[resp_processing, resp_ok])
return_value = await async_make_requests(parsed_data, "anyurl")
我得到:
results = await asyncio.gather(*tasks) RuntimeError: coroutine raised StopIteration
ok_function 工作正常,function_with_sleep 只有在不重复自身且不休眠的情况下才能正常工作。
我不知道这里出了什么问题。
【问题讨论】:
标签: python asynchronous python-asyncio