使用 asyncio 异步处理函数请求
Async processing of function requests using asyncio
我正在尝试对已在我的 class 中定义的请求进行 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 returns 当它收到 headers 时;它不希望响应完成。 (这会让您对状态代码做出反应,而无需等待整个 body 响应。)
您需要等待可以做到这一点的东西。如果您期望包含文本的响应,那将是 response.text
。如果您期望 JSON,那就是 response.json
。这看起来像
response = await session.get(url)
return await response.text()
我正在尝试对已在我的 class 中定义的请求进行 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 returns 当它收到 headers 时;它不希望响应完成。 (这会让您对状态代码做出反应,而无需等待整个 body 响应。)
您需要等待可以做到这一点的东西。如果您期望包含文本的响应,那将是 response.text
。如果您期望 JSON,那就是 response.json
。这看起来像
response = await session.get(url)
return await response.text()