Search code examples
pythonpython-3.xasync-awaitpython-asyncioaiohttp

How to resolve an aiohttp json future?


import asyncio
import Response
import aiohttp

async def resolve_response_json(res):
    new_res = Response()
    async with res:
        new_res.status = res.status
        new_res.json = await res.json()
    return new_res

class Client:
    async def request(url):
        async with aiohttp.ClientSession() as sess:
            res = await sess.get(url=url)
        return await resolve_response_json(res).json

client = Client()
loop = asyncio.get_event_loop()
value = loop.run_until_complete(client.request('https://example.com/api/v1/resource'))

Why does this piece of code give me:

>       return await resolve_response_json(res).json
E       AttributeError: 'coroutine' object has no attribute 'json'

I thought that the await keyword always returns an actual value. If it actually does, why is my code throwing this error?

Or am I just silly and probably forgot to put an await somewhere?


Solution

  • You are awaiting resolve_response_json(res).json, not resolve_response_json(res).

    Change it to (await resolve_response_json(res)).json may work.