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

标签 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
    

    所以这就是我制作 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_stringdays_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/

    相关文章:

    python - 从件号获取位置id的算法

    python - 解析引号和转义字符 CSV 文件

    python - 如何从 Python 运行 R 脚本中包含的函数? R 函数的输入将来自 Python

    python - 如何删除 python - mechanize 中的控件?

    python - 将 3D 矩阵与 2D 矩阵相乘

    python - 从 Python 中的字典列表创建新字典

    python - Python中的 'print'是什么?

    python - 打包 Ruby 或 Python 应用程序进行分发?

    python - SQLAlchemy,急切加载 postgresql INET/CIDR 关系

    python - 如果文件不存在,则优雅退出