如何解决 aiohttp json 的未来?
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'))
为什么这段代码给我:
> return await resolve_response_json(res).json
E AttributeError: 'coroutine' object has no attribute 'json'
我认为 await
关键字总是 returns 一个实际值。如果确实如此,为什么我的代码会抛出此错误?
还是我太傻了,可能忘了在某处放一个 await
?
您正在等待 resolve_response_json(res).json
,而不是 resolve_response_json(res)
。
将其更改为 (await resolve_response_json(res)).json
可能有效。
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
关键字总是 returns 一个实际值。如果确实如此,为什么我的代码会抛出此错误?
还是我太傻了,可能忘了在某处放一个 await
?
您正在等待 resolve_response_json(res).json
,而不是 resolve_response_json(res)
。
将其更改为 (await resolve_response_json(res)).json
可能有效。