【问题标题】:How to resolve an aiohttp json future?如何解决 aiohttp json 未来?
【发布时间】:2018-10-22 08:10:25
【问题描述】:
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'))

为什么这段代码给我:

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

我认为await 关键字总是返回一个实际值。如果确实如此,为什么我的代码会抛出此错误?

或者我只是很傻,可能忘了在某个地方放一个await

【问题讨论】:

  • 始终附加您的完整堆栈。哪一行给你这个错误?
  • 抱歉,我更新了问题

标签: python python-3.x async-await python-asyncio aiohttp


【解决方案1】:

您正在等待resolve_response_json(res).json,而不是resolve_response_json(res)

将其更改为(await resolve_response_json(res)).json 可能会起作用。

【讨论】:

    猜你喜欢
    • 2022-12-30
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多