简体   繁体   English

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

[英]How to pass a list of values, dynamically, as multiple Python requests parameters?

I'm new to Python.我是 Python 的新手。 Trying to automate some painful API calls using the Python requests module.尝试使用 Python requests模块自动化一些痛苦的 API 调用。 Getting pretty close, but can't figure out how to pass lists of timestamps as request parameters非常接近,但无法弄清楚如何将时间戳列表作为request parameters传递

Example: Generate list of lastModified timestamps示例:生成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

Results:结果:

['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']

Example 2: Create the request call示例 2:创建request调用

  • Here is (obviously) where my problem is.这是(显然)我的问题所在。 I tried to flesh out a function to handle it, but its not even close!我试图充实一个函数来处理它,但它甚至没有关闭!
  • How do I pass the first timestamp in the list as the lastModifiedStart parameter?如何将列表中的第一个时间戳作为lastModifiedStart参数传递? AND
  • Pass the second timestamp in the list as the lastModifiedEnd parameter?将列表中的第二个时间戳作为lastModifiedEnd参数传递?
  • Then so on until all timestamps have been tried?然后依此类推,直到尝试了所有时间戳?
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)

I know this isn't an easy solve (its taken me days and days to get this far), but any guidance on how to tackle this would be appreciated.我知道这不是一个简单的解决方案(我花了几天时间才走到这一步),但任何关于如何解决这个问题的指导都将不胜感激。

Thank you谢谢

EDIT 1: This adjusted function works great!编辑 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)

The standard trick for extracting pairs of consecutive items from a list is:从列表中提取连续项目对的标准技巧是:

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

So your code needs to be something like:所以你的代码需要是这样的:

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)

I hope I've understood correctly what it is you're trying to do.我希望我已经正确理解了你想要做什么。

So basically what you want to do is to chunk the list by 2 elements, and then unpack those 2 element lists and pass them to functions, consider something like the following generator:所以基本上你想要做的是将列表分成 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]

And then you can use it like the following:然后你可以像下面这样使用它:

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

Hope this helps希望这可以帮助

Edit: I'm not sure if you want to pass the variables by pairs that overlap or don't, if you want them to overlap like (0,1) (1,2) (2,3)... instead of (0,1) (2,3) (4,5)... then use the version of "chunks" below:编辑:我不确定您是否想通过重叠或不重叠的对传递变量,如果您希望它们像 (0,1) (1,2) (2,3) 一样重叠...而不是(0,1) (2,3) (4,5)... 然后使用下面的“块”版本:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM