URL中具有不同变量的多个API

2024-03-28 12:45:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Python,并且有一个关于for和if循环的问题。这是我的设想:

  • 我有一个使用request.get进行API调用的端点
  • 我需要检索所有历史数据
  • 我有一个开始日期(2017-06-17)

所以我需要进行多个API调用,因为它们的周期限制为60天。所以我的代码是这样的:

date = datetime.strptime("2017-06-17", "%Y-%m-%d")         # Start Date
current_date = date.date()                                 # timedelta need date object so i make it a date object
days_after = (current_date+timedelta(days=60)).isoformat() # days_after is set to 60-days because limit in API
date_string = current_date.strftime('%Y-%m-%d')            # made to string again since API need string not date object

这就是我如何制作60天的dates。从2017-06-17开始并提前60天

以下是我发出API请求的方式:

response = requests.get("https://reporting-api/campaign?token=xxxxxxxxxx&format=json&fromDate="+date_string+"&toDate="+days_after)
response_data = response.json()  # Added this because i am writing temprorary to a JSON file

以下是我写入JSON文件的方式:

if response_data:
    print("WE GOT DATA")              # Debugging
    data = response.json()            # This is duplicate?
    with open('data.json', 'w') as f: # Open my data.json file as write
        json.dump(data, f)            # dumps my json-data from API to the file
else:
    print("NO DATA")                  # Debugging if no data / response. Should make a skip statement here

因此,我的问题是如何继续我的代码,以便每次我从2017-06-17开始进行API调用时,日期date_stringdays_after应该向前60天执行每个API调用,并将这些数据附加到data.json。我可能需要一些循环什么的

请注意,我已经使用Python 3天了,请温柔一点。 谢谢


Tags: to代码apijsondatagetdatestring
1条回答
网友
1楼 · 发布于 2024-03-28 12:45:38

您可以使用while循环来更改开始和结束日期,直到满足指定的条件。此外,您还可以为每次运行将响应附加到文件中。下面的示例中,我使用了“今天”的日期:

import os
from datetime import datetime, timedelta

x = 0 
y = 60

date = datetime.strptime("2017-06-17", "%Y-%m-%d")
current_date = date.date() 
date_start = current_date+timedelta(days=x)

while date_start < datetime.now().date(): 
    date_start = current_date+timedelta(days=x)
    days_after = current_date+timedelta(days=y)
    x = x + 60
    y = y + 60

    response = requests.get("https://reporting-api/campaign?token=xxxxxxxxxx&format=json&fromDate="+date_start.isoformat() +"&toDate="+days_after.isoformat())

    response_data = response.json()
    if response_data:
        print("WE GOT DATA")      
        data = response.json()   

        #create a file if not exists or append new data to it.
        if os.path.exists('data.json'):
            append_write = 'a' # append if already exists
        else:
            append_write = 'w' # make a new file if not
        with open('data.json', append_write) as f: 
            json.dump(data, f)            
    else:
        print("NO DATA")

基本上,每次运行的开始和结束时间都会增加60天,并附加到data.json文件中

相关问题 更多 >