Python 使用asyncio异步处理函数请求
我正在尝试对类中定义的请求实现aiohttp异步处理,如下所示:Python 使用asyncio异步处理函数请求,python,python-3.x,async-await,python-asyncio,aiohttp,Python,Python 3.x,Async Await,Python Asyncio,Aiohttp,我正在尝试对类中定义的请求实现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 d
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()
当您等待类似于session.response
的消息时,I/O将启动,但aiohttp在接收到报头时返回;它不希望响应完成。(这将允许您对状态代码做出反应,而无需等待整个响应主体。)
你需要等待这样的事情发生。如果您期望的是包含文本的响应,则应该是response.text
。如果您需要的是JSON,那就是response.JSON
。这看起来像
response = await session.get(url)
return await response.text()
非常感谢。就这样:)谢谢你!就这样:)