我正在学习 Python 并且有一个关于 for 和 if 循环的问题。这是我的场景:
所以我需要进行多次 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
所以这就是我制作
dates
的方式为期 60 天。从 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_string
和 days_after
应该去 60 天前 对于每个 API 调用并将这些数据附加到 data.json
.我可能需要一些 for 循环之类的?请注意,我已经使用 Python 3 天了,请保持温和。
谢谢!
最佳答案
您可以使用 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 文件中。
关于python - URL 中具有不同变量的多个 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60547910/