使用Python和Aiohttp链接请求

2024-10-03 02:34:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉python中的异步编程,一直在使用aiohttp编写脚本,该脚本从get请求获取数据,并将响应中的特定变量传递给另一个post请求。下面是我尝试过的示例:

async def fetch1(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:      # First hit to the url 
            data = resp.json()                    # Grab response
            return await fetch2(data['uuid'])     # Pass uuid to the second function for post request

async def fetch2(id):
    url2 = "http://httpbin.org/post"
    params = {'id': id}
    async with aiohttp.ClientSession() as session:
        async with session.post(url2,data=params) as resp:
            return await resp.json()


async def main():
    url = 'http://httpbin.org/uuid'
    data = await fetch1(url)


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

当我执行脚本时,出现以下错误:

Traceback (most recent call last):
  File ".\benchmark.py", line 27, in <module>
   loop.run_until_complete(main())
  File "C:\ProgramFiles\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2288.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 616, in run_until_complete
  return future.result()
  File ".\benchmark.py", line 22, in main
   data = await fetch1(url)
  File ".\benchmark.py", line 10, in fetch1
   return fetch2(data['uuid'])
TypeError: 'coroutine' object is not subscriptable
sys:1: RuntimeWarning: coroutine 'ClientResponse.json' was never awaited

我知道协同程序是一个发电机,但我如何继续,任何帮助将不胜感激


Tags: loopurldataasyncreturnuuidmainsession
1条回答
网友
1楼 · 发布于 2024-10-03 02:34:51

错误显示为coroutine 'ClientResponse.json' was never awaited,这意味着它必须在json部分前面有一个await。这是因为您使用的是异步函数

async def fetch1(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:      # First hit to the url 
            data = await resp.json()                    # Grab response
            return await fetch2(data['uuid'])     # Pass uuid to the second function for post request

async def fetch2(id):
    url2 = "http://httpbin.org/post"
    params = {'id': id}
    async with aiohttp.ClientSession() as session:
        async with session.post(url2,data=params) as resp:
            return await resp.json()


async def main():
    url = 'http://httpbin.org/uuid'
    data = await fetch1(url)


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

相关问题 更多 >