【问题标题】:Chaining Requests using Python and Aiohttp使用 Python 和 Aiohttp 链接请求
【发布时间】:2021-06-05 12:31:49
【问题描述】:

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

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

【问题讨论】:

    标签: python asynchronous async-await aiohttp


    【解决方案1】:

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

    【讨论】:

    • 但这是执行此类操作的最佳方式吗?只是想知道它是否遵循异步行为
    • @CharlieChap 好吧,您正在执行异步请求,因此看起来不错。您可能想在codereview.stackexchange.com 中发帖以征求对您代码的意见。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-03
    • 2021-02-15
    • 1970-01-01
    • 2022-10-08
    • 2022-07-08
    相关资源
    最近更新 更多