1

I am trying to achieve aiohttp async processing of requests that have been defined in my class as follows:

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

When running to get the results from the get_async_requests function, i am getting the following error:

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

Where am i going wrong in the code? Thank you in advance

1 Answer 1

3

When you await something like session.response, the I/O starts, but aiohttp returns when it receives the headers; it doesn't want for the response to finish. (This would let you react to a status code without waiting for the entire body of the response.)

You need to await something that does that. If you're expecting a response that contains text, that would be response.text. If you're expecting JSON, that's response.json. This would look something like

response = await session.get(url)
return await response.text()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.