简体   繁体   English

嵌套 function 以异步方式调用 python

[英]Nested function call in async way python

I have an api that returns response of pagination only 10 records at a time.我有一个 api 一次只返回 10 条记录的分页响应。 I want to process 10 record (index=0 and limit=10) then next 10(index=10 and limit=10) and so on till it returns empty array.我想处理 10 条记录(索引=0 和限制=10),然后处理下 10 条记录(索引=10 和限制=10),依此类推,直到它返回空数组。

I want to do it in async way.我想以异步方式进行。

I am using the following deps:我正在使用以下部门:

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

The code is:代码是:

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"
        )

I issue is that it works fine for first time but when i am calling the method getData(session, id, limit, limit+10) again from async def getData(id, token, index, limit).我的问题是它第一次工作正常但是当我再次从 async def getData(id, token, index, limit) 调用方法 getData(session, id, limit, limit+10) 时。 It is not been called.它没有被调用。

How can i resolve the issue?我该如何解决这个问题?

There are a few issues I see in your code.我在您的代码中看到了一些问题。

First, and this is what you talk about, is the getData method.首先,这就是您所说的,是getData方法。 It is unclear to me a bit by looking at the code, what is that "second" getData .通过查看代码,我有点不清楚“第二个” getData是什么。 In the function definition your arguments are getData(id, token, index, limit) , but when you call it from within the function you call it with getData(session, id, limit, limit+10) where the id is the second parameter.在 function 定义中,您的 arguments 是getData(id, token, index, limit) ,但是当您从 function 中调用它时,您使用getData(session, id, limit, limit+10)调用它,其中id是第二个参数. Is that intentional?那是故意的吗? This looks to me like there is another getData method, or it's a bug.在我看来,这好像还有另一个getData方法,或者它是一个错误。

In case of the first option: (a) you probably need to show us that code as well, as it's important for us to be able to give you better responses, and (b), more importantly, it will not work.如果是第一个选项:(a) 您可能还需要向我们展示该代码,因为这对我们能够给您更好的响应很重要,并且 (b),更重要的是,它不起作用。 Python doesn't support overloading and the getData you are referencing from within the wrapping getData is the same wrapping method. Python 不支持重载,并且您在包装getData中引用的getData是相同的包装方法。

In case it's the second option: (a) you might have an issue with the function parameters, and (b) - you are missing an await before the getData (ie await getData ).如果是第二个选项:(a) 您可能遇到 function 参数问题,以及 (b) - 您在getData之前缺少await (即await getData )。 This is actually probably also relevant in case it's the "first option".如果它是“第一选择”,这实际上也可能是相关的。


Other than that, your exception handling is redundant.除此之外,您的异常处理是多余的。 You basically just re raise the exception, so I don't see any point in having the try-catch blocks.您基本上只是重新引发异常,所以我认为拥有try-catch块没有任何意义。 Even more, for some reason in the first method, you create an Exception from the base exception class (not to be confused with BaseException ).更重要的是,出于某种原因,在第一种方法中,您从基本异常 class 创建了一个Exception (不要与BaseException混淆)。 Just don't have the try block.只是没有try块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM