aiohttp
库来发出 HTTP GET 请求,并使用 GitHub v3 REST API 进行练习。这是我的基本请求代码:
# Python Standard Library imports
import asyncio
import sys
# External library imports
import aiohttp
# GitHub API v3 REST endpoint for licenses
GITHUB_URL: str = "https://api.github.com/licenses"
# GitHub query headers
GITHUB_HEADERS: dict = {
"Accept": "application/vnd.github.v3+json"
}
async def main():
async with aiohttp.ClientSession() as session:
async with session.get(GITHUB_URL, headers = GITHUB_HEADERS) as GitHub_response:
print(GitHub_response.content)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
sys.exit(0)
代码运行没有错误,但关键的
print(GitHub_response.content
行给了我:
这不是我所期望的。到底什么是
StreamReader
对象???
我期望的是
curl
命令 curl -H "Accept: application/vnd.github.v3+json" "https://api.github.com/licenses
的 JSON 输出
会给我,看起来像:
[
{
"key": "agpl-3.0",
"name": "GNU Affero General Public License v3.0",
"spdx_id": "AGPL-3.0",
"url": "https://api.github.com/licenses/agpl-3.0",
"node_id": "MDc6TGljZW5zZTE="
},
{
"key": "bsd-2-clause",
"name": "BSD 2-Clause \"Simplified\" License",
"spdx_id": "BSD-2-Clause",
"url": "https://api.github.com/licenses/bsd-2-clause",
"node_id": "MDc6TGljZW5zZTQ="
},
.....
我尝试用
print()
替换我的 print(GitHub_response.json())
行,但这给了我:
<coroutine object ClientResponse.json at 0x7f7e452b5e00>
所以它仍然不是我期待的 JSON。
我做错了什么?如何修复我的 Python 代码,以便获得实际的 JSON 响应 with
aiohttp
?
谢谢你。
P.S. 我尝试使用 Python
requests
库执行上述操作。在这种情况下,响应的内容是一个 bytes
对象,在使用 decode("utf8")
库中的 json.dumps()
将其转换为实际的 JSON 之前,我必须先 json
。不确定这些信息是否有助于弄清楚我在使用 aiohttp
时搞砸了什么。
“content”是 StreamReader 的实例。这提供了一个coroutine“读取”,读取以字符串形式返回内容。将以下示例插入您的代码中,您应该会得到预期的结果。
x = await GitHub_response.content.read()
print(x.decode("utf8"))
可以使用:
await GitHub_response.text()