You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

aiohttp ClientSession发送带JSON的GET请求协程报错排查

报错根因

你看到的ValueError: a coroutine was expected错误,是asyncio.run()传参不对导致的:

  • 用async def定义的main是异步函数,直接写main传进去的是函数本身,不是能运行的协程
  • asyncio.run()要求传入的是调用异步函数后返回的协程对象,你漏了函数调用必须加的括号。
修复方法

把代码最后一行从

asyncio.run(main)

改成

asyncio.run(main())

就行。修复后的完整可运行代码如下:

import aiohttp
import asyncio

url = 'http://10.200.200.223:5000/bacnet/read/multiple'

my_rtu_reads = {
    "read": [    
        {
            "address": "10.200.200.27",
            "object_type": "binaryOutput",
            "object_instance": "3"
        },
        {
            "address": "10.200.200.27",
            "object_type": "binaryOutput",
            "object_instance": "4"
        },
        {
            "address": "10.200.200.27",
            "object_type": "binaryOutput",
            "object_instance": "5"
        },
        {
            "address": "10.200.200.27",
            "object_type": "binaryOutput",
            "object_instance": "6"
        }
    ]
}

async def main():
    async with aiohttp.ClientSession() as session:
        async with session.get(url, json=my_rtu_reads) as resp:
            print(resp.status)
            print(await resp.text())

if __name__ == "__main__":
    asyncio.run(main())
额外提醒
  • 虽然requests支持给GET请求传json参数自动附加JSON请求体,但HTTP规范本身不推荐GET请求携带请求体,部分服务端、网关、代理会直接丢弃GET请求的body内容。要是改完协程调用的问题后接口返回不符合预期,可以先确认目标接口是否真的支持GET传JSON,不行就换成POST请求。
  • 加上if __name__ == "__main__":的入口判断,能避免多进程运行时重复启动事件循环抛出异常。

内容的提问来源于stack exchange,提问作者bbartling

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 01:39:19