我需要相对拨打API,但是API端点将我限制为每分钟100个呼叫。我有一个列表,该列表用作API调用的数据(我正在使用请求来调用API)。
LLES说该列表有227个元素。我需要为每个元素进行单独的API调用(这就是API端点的工作方式)。我的问题是,我该如何使用前100个元素并使用它们进行100个单独的API调用,然后等待60秒,然后重复接下来的100个元素,再次入睡60秒,然后重复最后27个元素?
我可以自己的API自己。我可以使用Sleep()暂停该功能,我可以处理API呼叫的响应。它只是将我的迭代循环分解成我正在挣扎的部分。 我的代码看起来有点像这样:
list_of_data = [{key1:value1, key2:value2, ... key227:value227}]
total_data=len(list_of_data_
for count in range(0, total_data):
if count <= total_data: # limit the api calls to the list length
data = list_of_data[count] # Pull out the current list element
count = count + 1 # step counter to the next list element
url = 'https:api.com/endpoint'
params = {
'param_1': data[key1],
'param2': data[key2],
...
'param227': data[key227]
}
headers = {some headers}
response = requests.get(url=url,params=params,headers=headers,)
json = response.json()
<process the json>
先前谢谢。
听到您对执行感到满意,并且您正在研究如何执行API呼叫。 重试的能力
这是想到的关键点。是的,我们可以睡60年代,但是每个API电话都不能保证成功。一批可能会成功,第二批可能失败。您不想处于批次之间的批次失败时需要从批次#1开始的情况。 输入的存储我建议考虑一种存储批处理文件的方法,每个文件一批。这可能是一个斑点项目,消息队列消息,本地文件等。考虑文件的队列时,处理一个文件时,将其删除并处理呼吸。如果API呼叫未成功,请查看如何重试。
过程
def process():
try:
api_call()
except Exception as e:
print(f"Error processing file {file}: {e}")
#move file to a retry folder
for file in files:
process(file)
pause(60_seconds)
主要点ID制作,您的批量大小不得超过100。我总是建议确保每批成功的成功,以及重试的能力。