使用asyncio异步处理函数请求



我正在尝试实现类中定义的请求的aiohttp异步处理,如下所示:

class Async():    
async def get_service_1(self, zip_code, session):
url = SERVICE1_ENDPOINT.format(zip_code)
response = await session.request('GET', url)
return await response
async def get_service_2(self, zip_code, session):
url = SERVICE2_ENDPOINT.format(zip_code)
response = await session.request('GET', url)
return await response
async def gather(self, zip_code):
async with aiohttp.ClientSession() as session:
return await asyncio.gather(
self.get_service_1(zip_code, session),
self.get_service_2(zip_code, session)
)
def get_async_requests(self, zip_code):
asyncio.set_event_loop(asyncio.SelectorEventLoop())
loop = asyncio.get_event_loop()
results = loop.run_until_complete(self.gather(zip_code))
loop.close()
return results

当运行以从get_async_requests函数获取结果时,我得到以下错误:

TypeError: object ClientResponse can't be used in 'await' expression

我的代码哪里出错了?提前感谢

当您等待类似session.response的东西时,I/O启动,但aiohttp在接收到标头时返回;它不希望响应结束。(这将使您对状态代码做出反应,而无需等待整个响应。(

你需要等待这样的事情。如果您希望得到一个包含文本的响应,那么应该是response.text。如果您期望的是JSON,那就是response.json。这看起来像

response = await session.get(url)
return await response.text()

最新更新