python - 使用 Python 从 REST API 获取大型分页数据

标签 python json python-3.x rest api

我正在从 REST API 中提取数据。问题是数据量很大,因此响应是分页的。我通过首先读取有多少页数据,然后迭代每个页面的请求来解决这个问题。这里唯一的问题是页面总数约为 1.5K,这需要大量时间来实际获取并附加到 CSV。有没有更快的解决方法?

这是我的目标端点:https://developer.keeptruckin.com/reference#get-logs

import requests
import json
import csv
url='https://api.keeptruckin.com/v1/logs?start_date=2019-03-09'
header={'x-api-key':'API KEY HERE'}
r=requests.get(url,headers=header)
result=r.json()
result = json.loads(r.text)
num_pages=result['pagination']['total']
print(num_pages)
for page in range (2,num_pages+1):
    r=requests.get(url,headers=header, params={'page_no': page})
    result=r.json()
    result = json.loads(r.text)
    csvheader=['First Name','Last Name','Date','Time','Type','Location']
    with open('myfile.csv', 'a+', newline='') as csvfile:
        writer = csv.writer(csvfile, csv.QUOTE_ALL)
        ##writer.writerow(csvheader)
        for log in result['logs']:
            username = log['log']['driver']['username']
            first_name=log['log']['driver']['first_name']
            last_name=log['log']['driver']['last_name']
            for event in log['log']['events']:
                start_time = event['event']['start_time']
                date, time = start_time.split('T')
                event_type = event['event']['type']
                location = event['event']['location']
                if not location:
                    location = "N/A"
                if (username=="barmx1045"  or username=="aposx001" or username=="mcqkl002" or username=="coudx014" or username=="ruscx013" or username=="loumx001" or username=="robkr002" or username=="masgx009"or username=="coxed001" or username=="mcamx009" or username=="linmx024" or username=="woldj002" or username=="fosbl004"):
                    writer.writerow((first_name, last_name,date, time, event_type, location))

最佳答案

第一个选项:大多数分页回复都有可以编辑的页面大小。 https://developer.keeptruckin.com/reference#pagination 尝试将 per_page 字段更新为 100,而不是默认的每次拉取 25。

第二个选项:您可能可以通过使用多个线程/进程并拆分每个线程/进程负责的页面部分来一次拉取多个页面。

关于python - 使用 Python 从 REST API 获取大型分页数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56370305/

相关文章:

Python - 无法转换为 int

Javascript-如何遍历无效的 JSON

python-3.x - 一些提高时间复杂度的建议

python - 编写一个程序,要求用户输入 5 个数字,并输出这些数字中最大的数字和最小的数字。

python - django 变量可用于所有 View

python - 使用 pandas 修改捕获组

python - 我可以在没有 POST 的情况下在 python 中实现 Web 用户身份验证系统吗?

javascript - 通用 JSON 对象

java - java中通过socket传输文件的最佳方法

python - 在 python 中使用套接字发送文本和二进制文件