分页API良好做法

时间:2019-05-27 09:28:12

标签: python flask

我的主要功能:

def get_data():
    try:
        response = send_request_to_get_data()

        // will get one dict output looks like :
        {
          "data": ['some datas.....'],
          "next": "api/data?top=100&skip=200",
        }

        if response.status_code == 200:
            if response.json().get("next"):
                first_paginated_response = get_paginated_data(response.json().get("next"))

                if response.status_code == 200:
                    if first_paginated_response.json().get("next"):
                        second_paginated_response = get_paginated_data(response.json().get("next"))

                        if response.status_code == 200:
                           if second_paginated_response.json().get("next"):
                               print('again...again....again....again...again)


def send_request_to_get_data():
    return rq.get('https://example.com')


def get_paginated_data(paginated):
    url = "https://example.com/{next}".format(next=paginated)
    return rq.get(url)

如果响应“ next”键,我需要发送另一个分页api请求,但是我的if语句看起来很奇怪。

什么是好的方法?

1 个答案:

答案 0 :(得分:1)

您可以使用response = send_request_to_get_data() data = response['data'] while response.status_code == 200 and response.json().get("next"): response = get_paginated_data(response.json().get("next")) data.extend(response['data']) 循环并像这样保存数据:

{{1}}