【问题标题】:End API Pagination Loop in Python在 Python 中结束 API 分页循环
【发布时间】:2022-02-18 22:29:16
【问题描述】:

我正在尝试构建一个 Python 脚本,通过他们的 API 从 Chargebee 检索所有发票。但是,我有点短,因为我不知道一旦循环到达最后一页如何正确结束循环。我当前的解决方案包括在 URL 与最后一页相同时插入一个中断。不幸的是,这不是很可持续,因为每次最后一个 next_offset 值更改时我都必须更新它。

我当前的代码如下所示:

import requests
import json
import pandas as pd
from requests.auth import HTTPBasicAuth
from pandas import json_normalize 

invoices = []
customers = []

def GetInvoices():
    url = 'https://company.chargebee.com/api/v2/invoices?limit=100&offset='
    url1 = 'https://company.chargebee.com/api/v2/invoices?limit=100&offset='
    while url:
        print('----')
        print('Requesting', url)
        response = requests.get(url, auth=HTTPBasicAuth('APIKEY','pass'))
        data = response.json()

        invoices.extend(data['list'])

        if url == 'https://company.chargebee.com/api/v2/invoices?limit=100&offset=["1507705200000","78206775"]':
            df = json_normalize(invoices)
            df.to_csv('InvoicesUS.csv')
            print('----')
            print('Invoice list has been exported!')
            break

        else:
            url = url1 + data['next_offset']

我对 Python 很陌生,所以脚本中可能有很多不必要的东西。它正在工作,但我想找到一种方法来通过 API 进行分页,并在附加最后一页后关闭循环。

谢谢!

【问题讨论】:

    标签: python api loops pagination chargebee


    【解决方案1】:

    使用 try/except 找到了问题的解决方案。现在的代码如下所示:

    import requests
    import json
    import pandas as pd
    from requests.auth import HTTPBasicAuth
    from pandas import json_normalize
    
    invoices = []
    
    url = 'https://company.chargebee.com/api/v2/invoices?limit=100&offset='
    url1 = 'https://company.chargebee.com/api/v2/invoices?limit=100&offset='
    
    while url:
        try:
            print('----')
            print('Requesting', url)
            response = requests.get(url, auth=HTTPBasicAuth('APIKEY','pass'))
            data = response.json()
    
            invoices.extend(data['list'])
            
            url = url1 + data['next_offset']
    
        except KeyError:
            df = json_normalize(invoicesUS)
            print('----')
            print('Invoice list has been exported!')
            break
    

    【讨论】:

      猜你喜欢
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      相关资源
      最近更新 更多