代码之家  ›  专栏  ›  技术社区  ›  Avenger

python异步方式的嵌套函数调用

  •  0
  • Avenger  · 技术社区  · 5 年前

    我有一个api,一次只返回10条记录的分页响应。我想处理10条记录(index=0和limit=10),然后处理下一条10(index=10和limit=10),依此类推,直到它返回空数组。

    我正在使用以下DEP:

    yarl==1.6.0
    Mako==1.1.3
    asyncio==3.4.3
    aiohttp==3.6.2
    

    代码是:

    loop = asyncio.get_event_loop()
    loop.run_until_complete(getData(id, token,0, 10))
    logger.info("processed all data")
    
    
    
    async def getData(id, token, index, limit):
        try:
            async with aiohttp.ClientSession() as session:
                response = await fetch_data_from_api(session, id, token, index, limit)
                if response == []:
                    logger.info('Fetched all data')
                else:
                    # process data(response)
                    getData(session, id, limit, limit+10)
        except Exception as ex:
            raise Exception(ex)
    
    
    async def fetch_data_from_api(
            session, id, token, index, limit
    ):
        try:
            url = f"http://localhost:8080/{id}?index={index}&limit={limit}"
            async with session.post(
                    url=url,
                    headers={"Authorization": token}
            ) as response:
                response.raise_for_status()
                response = await response.json()
                return json.loads(json.dumps(response))
        except Exception as ex:
            raise Exception(
                f"Exception {ex} occurred"
            )
    
    

    我的问题是,它第一次工作正常,但当我从异步def getData(id、token、index、limit)再次调用方法getData(session、id、limit、limit+10)时。没有人叫它。

    我如何解决这个问题?

    0 回复  |  直到 5 年前
        1
  •  1
  •   Mickey    5 年前

    我在您的代码中看到了一些问题。

    首先,这就是你所说的,是 getData 通过查看代码,我有点不清楚“秒”是什么 获取数据 . 在函数定义中,参数是 getData(id, token, index, limit) getData(session, id, limit, limit+10) 在哪里 id 是第二个参数。这是故意的吗?在我看来,这是另一个 获取数据

    获取数据 获取数据 是相同的包装方法。

    await 获取数据 await getData


    除此之外,您的异常处理是多余的。基本上,您只需重新引发异常,因此我不认为有任何意义 try-catch Exception 从基本异常类(不要与 BaseException ). 只是没有足够的时间 try