簡體   English   中英

python遞歸裝飾器

[英]python recursive decorator

我有一個函數返回API調用中的字典列表。 API可以為每個請求返回最多100條記錄。 記錄存儲在頁面中,每頁包含100條記錄。

def call_api(page):
    return list_of_records

我需要的是一個裝飾器,每次返回100個帶有頁面參數= + 1的記錄時都可以重新運行該函數。

就像是:

if len(list_of_records) == 100:
   call_api(page +=1)

最終輸出應該是包含所有記錄的單個列表

定義一個遞歸調用函數的裝飾器當然是可能的。

以下是這種裝飾器在您的情況下的外觀:

import functools

def with_pages(func):
    @functools.wraps(func)

    def wrapper(page):
        list_of_records = []
        partial_list = func(page)
        list_of_records.extend(partial_list)
        while len(partial_list) == 100:  # there is probably a better condition to check if you are at the last page (e.g. next_page URI in api reply)
            page += 1
            partial_list = func(page)
            list_of_records.extend(partial_list)
        return list_of_records
    return wrapper

@with_pages
def call_api(page):
    # api interaction creating list_of_records_on_a_page
    return list_of_records_on_a_page

或者,您可以調整call_api ,以便可以遞歸調用它。

就像是:

def call_api(page, list_of_records=[]):
    partial_list = ... # the records you get from the api
    list_of_records.extend(partial_list)
    # often api provide the url for the next page or some more reliable info
    # about whether or not you are on the last page, i.e. testing for the length
    # of the reply is probably not the best strategy
    if len(partial_list) == 100:
        # time.sleep(0.2)  # just to not end up with to many requests in a short period of time
        call_api(page + 1, list_of_records)
    return list_of_records

只需調用call_api(1)即可獲取所有頁面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM