如何将值列表作为多个Python请求参数动态传递?

2024-04-23 06:40:01 发布

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

我是Python新手。尝试使用Python requests模块自动化一些痛苦的API调用。非常接近,但不知道如何将时间戳列表作为request parameters传递

示例:生成lastModified时间戳列表

import datetime
from datetime import datetime, timedelta

earliest_ts_str = '2020-10-01T15:00:00Z'
earliest_ts_obj = datetime.strptime(earliest_ts_str, timestamp_format)

#bottom_ts_obj = earliest_ts_obj.replace(second=0, microsecond=0, minute=0)

latest_ts_str = '2020-10-01T23:00:00Z'
latest_ts_obj = datetime.strptime(latest_ts_str, timestamp_format)

ts_raw = []
while earliest_ts_obj < latest_ts_obj:
    ts_raw.append(earliest_ts_obj)
    earliest_ts_obj += timedelta(hours=1)

ts_raw.append(latest_ts_obj)

ts_formatted = [d.strftime('%Y-%m-%dT%H:%M:%SZ') for d in ts_raw]
ts_formatted

结果:

['2020-10-01T15:00:00Z',
 '2020-10-01T16:00:00Z',
 '2020-10-01T17:00:00Z',
 '2020-10-01T18:00:00Z',
 '2020-10-01T19:00:00Z',
 '2020-10-01T20:00:00Z',
 '2020-10-01T21:00:00Z',
 '2020-10-01T22:00:00Z',
 '2020-10-01T23:00:00Z']

示例2:创建request调用

  • 这(显然)就是我的问题所在。我试图充实出一个函数来处理它,但它甚至不接近
  • 如何将列表中的第一个时间戳作为lastModifiedStart参数传递?
  • 将列表中的第二个时间戳作为lastModifiedEnd参数传递?
  • 然后继续,直到所有的时间戳都试过了
import requests

method = 'get'
base_url = 'https://sandbox-api.com/'
api_type = 'items'
api_version = '/v1/'
api_path = api_type + api_version

api_key = 'myKey'

full_url = base_url + api_path

def make_historic_calls(last_mod_start, last_mod_end):
    last_mod_start = for ts in ts_formatted: ts
    last_mod_end = for ts in ts_formatted: ts
    parameters = {'api_key':api_key, 'lastModifiedStart': last_mod_start, 'lastModifiedEnd': last_mod_end}

    auth_header = {'Authorization': 'Basic <base64EncodedStringHere>'}

    resp_raw = requests.request(method, full_url, headers=auth_header, params=parameters)

    resp_processed = json.loads(resp_raw.content)

    resp_pretty = json.dumps(resp_processed, indent=2, sort_keys=True)

    return print(pretty)

test = make_historic_calls(ts_formatted, ts_formatted)

我知道这不是一个容易的解决办法(我花了好几天才走到这一步),但任何关于如何解决这一问题的指导都将不胜感激

多谢各位

编辑1:此调整功能非常有效

def make_historic_calls(ts_formatted):
    for last_mod_start, last_mod_end in zip(ts_formatted, ts_formatted[1:]):
        parameters = {'api_key':api_key, 'lastModifiedStart': last_mod_start, 'lastModifiedEnd': last_mod_end}

        auth_header = {'Authorization': 'Basic <base64EncodedString>'}

        resp_raw = requests.request(method, full_url, headers=auth_header, params=parameters)

        print(f'{resp_raw.url} Status Code: {str(resp_raw.status_code)}')

    return print(resp_raw)

test = make_historic_calls(ts_formatted)

Tags: apimodobjurldatetimeraw时间latest
2条回答

从列表中提取连续项对的标准技巧是:

for this_one, next_one in zip(my_list, my_list[1:]):
   ...

因此,您的代码需要类似于:

def make_historic_calls(ts_formatted):
    for last_mod_start, last_mod_end in zip(ts_formatted, ts_formatted[1:]):
        make the request using last_mod_start and last_mod_end
    return some value combining all of the results from your requests


make_historic_calls(ts_formatted)

我希望我已经正确地理解了你想做什么

基本上,你要做的是用2个元素将列表分组,然后解开这2个元素列表并将它们传递给函数,考虑下面的生成器:



def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]

然后您可以按如下方式使用它:

for first, second in chunks(iterable, 2):
    make_historic_calls(first, second)

希望这有帮助

编辑: 我不确定您是否希望通过重叠或不重叠的对来传递变量,是否希望它们像(0,1)(1,2)(2,3)一样重叠。。。而不是(0,1)(2,3)(4,5)。。。然后使用下面的“chunks”版本:

def chunks(l, n, repeat=True):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        additional = int(repeat)
        yield l[i:i + n + additional]

相关问题 更多 >