python - 偏移量为 100 的分页循环

标签 python api pagination

我正在编写一个代码,我从一个 API 获取记录,这个 API 实现了分页,最多允许 100 条记录。所以我必须循环 100 的倍数。目前,我的代码比较总记录和循环,从 offset 100 到 101,102,103 等。我希望它以 100(例如 100,200,300)为单位循环,并在偏移量大于总记录时立即停止。我不知道该怎么做,我有部分代码递增 1 而不是 100,并且在需要时不会停止。谁能帮我解决这个问题。

import pandas as pd
from pandas.io.json import json_normalize

#Token for Authorization
API_ACCESS_KEY = 'Token'
Accept='application/xml'

#Query Details that is passed in the URL
since = '2018-01-01'
until = '2018-02-01'
limit = '100'
offset = '0'
total = 'true'

def get():

    url_address = "https://mywebsite/web?offset="+str('0') 
    headers = {
        'Authorization': 'token={0}'.format(API_ACCESS_KEY),
        'Accept': Accept,
    }
    querystring = {"since":since,"until":until, "limit":limit, "total":total}


    # find out total number of pages
    r = requests.get(url=url_address, headers=headers, params=querystring).json()
    total_record = int(r['total'])
    print("Total record: " +str(total_record))

    # results will be appended to this list
    all_items = []

    # loop through all offset and return JSON object
    for offset in range(0, total_record):

        url = "https://mywebsite/web?offset="+str(offset)              
        response = requests.get(url=url, headers=headers, params=querystring).json()        
        all_items.append(response)       
        offset = offset + 100
        print(offset)

    # prettify JSON
    data = json.dumps(all_items, sort_keys=True, indent=4)

    return data

print(get())

目前,当我打印偏移量时,我看到了
总记录:345
100,
101、
102、

预期:
总记录:345
100,
200,
300
停止循环!

最佳答案

一种方法是改变

for offset in range(0, total_record):
    url = "https://mywebsite/web?offset="+str(offset)              
    response = requests.get(url=url, headers=headers, params=querystring).json()        
    all_items.append(response)       
    offset = offset + 100
    print(offset)

for offset in range(0, total_record, 100):
    url = "https://mywebsite/web?offset="+str(offset)              
    response = requests.get(url=url, headers=headers, params=querystring).json()        
    all_items.append(response)       
    print(offset)

因为你不能改变循环内的偏移量

关于python - 偏移量为 100 的分页循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57616108/

相关文章:

asp.net-mvc - MVC 4 中的过滤和分页

asp.net - 简单的 ASP.NET 无休止分页

Magento - 网格分页

python - 按列条件清理数据框

python - 全局名称 'key' 未定义

python - 从 Celery 队列获取结果时遇到问题

api - 仅用于 API 的 SSL 证书还是客户需要它们?

Python:将列表与范围列表合并

api - 以Magento为主要工具,并创建一个单一登录即可与其他第三方软件集成

java - 如何在 Android API 2.2 及更高版本中使用 Renderscript?