简体   繁体   English

在 Python 结束 API 分页循环

[英]End API Pagination Loop in Python

I am trying to build a Python script where I retrieve all the invoices from Chargebee through their API. I am, however, coming up a bit short as I do not know how to properly end the loop once it has reached the last page.我正在尝试构建一个 Python 脚本,在其中我通过 API 从 Chargebee 检索所有发票。但是,我有点短,因为我不知道如何在循环到达最后一页后正确结束循环。 My current solution consists of inserting a break when the URL is the same as the last page.我当前的解决方案包括在 URL 与最后一页相同时插入一个中断。 Unfortunately, this is not very sustainable as I have to update it every time the last next_offset value changes.不幸的是,这不是很可持续,因为每次最后一个 next_offset 值更改时我都必须更新它。

My current code looks like this:我当前的代码如下所示:

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']

I am very new to Python, so there might be a lot of unnecessary things in the script.我对 Python 很陌生,所以脚本中可能有很多不必要的东西。 It is working, but I would like to find a way to page through the API and close the loop once the last page has been appended.它正在工作,但我想找到一种方法来翻阅 API 并在附加最后一页后关闭循环。

Thank you!谢谢!

Found a solution to the problem by using try/except.通过使用 try/except 找到了问题的解决方案。 The code now looks like this:代码现在看起来像这样:

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

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

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