使用 Python 和 Aiohttp 链接请求

Chaining Requests using Python and Aiohttp

我是 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

我知道协程是一个生成器,但我该如何继续,任何帮助将不胜感激。

错误显示 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())