简体   繁体   English

While循环进行API调用,直到满足条件为止

[英]While loop to make API calls until a condition is met

I want to make API calls until a condition is met. 我想进行API调用,直到满足条件为止。 I figured I might use a while loop. 我认为我可能会使用while循环。

I have a JSON response from the server that is paginated. 我有来自分页服务器的JSON响应。

{
    "services": [
        {
            "id": "ABC12",
            "name": "Networks",
            "description": null,
            "status": "active",
            "teams": [
                {
                    "id": "XYZ12",
                    "type": "team_reference",
                    "summary": "Network Systems ",
                }
            ],
            "acknowledgement_timeout": null,
            "auto_resolve_timeout": null,
            "alert_grouping": "intelligent",
            "alert_grouping_timeout": null,
            "integrations": [],
            "response_play": null,
            "type": "service",
            "summary": "All Events",
        }
     ],
     "limit": 25,
     "offset": 0,
     "total": null,
     "more": true
}

limit - max I can set is 100.

offset - If specified, shows results from that point.

more - If TRUE, there are more results. If FALSE, that is the end.

for more info on this pagination - https://v2.developer.pagerduty.com/docs/pagination 有关此分页的更多信息-https: //v2.developer.pagerduty.com/docs/pagination

I need to match the name "Networks" and get its corresponding id "ABC12". 我需要匹配name “ Networks”并获取其对应的id “ ABC12”。 The problem is, I have to paginate make multiple calls to the API. 问题是,我必须分页对API进行多次调用。

I have written this so far. 到目前为止,我已经写过了。

import requests
import json
import urllib3

# Supress SSL warnings
urllib3.disable_warnings()

# API key
API_KEY = '12345asdfg'

def list_services():

    x = 25
    y = 0
    results = []

    url = f'https://api.pagerduty.com/services/?limit={x}&offset={y}'
    headers = {
        'Accept': 'application/vnd.pagerduty+json;version=2',
        'Authorization': 'Token token={token}'.format(token=API_KEY)
    }
    current_page = json.loads(requests.get(url, verify=False, headers=headers).content.decode('UTF-8'))
    results.append(current_page)

    while current_page['more'] == 'True':
        y = y + 1
        current_page = json.loads(requests.get(url, verify=False, headers=headers).content.decode('UTF-8'))
        results.append(current_page)
        print(results) # Does not print anything
    print(results) # Prints only the first call results, the while loop 
                   # doesn't seem to work.

if __name__ == '__main__':
    list_services()

the print(results) outside the while loop prints only the first API call results. while循环外的print(results)仅打印第一个API调用结果。 The while loop doesn't seem to work. while循环似乎不起作用。 But the code compiles without any errors. 但是代码编译没有任何错误。

  1. how do I set the value of x to 25 and make API calls and append the results to results until more is false? 如何将x的值设置为25并进行API调用并将结果附加到results直到more错误为假?

OR 要么

  1. how do I make multiple API calls until I find the match. 在找到匹配项之前,如何进行多个API调用。 If I found a match, then stop making the call. 如果找到匹配项,请停止拨打电话。

Or is there a better cleaner way to do this? 还是有更好的清洁方法来做到这一点?

This does not work because you never actually reassign the url variable once y is changed. 这是行不通的,因为一旦更改了y,就永远不会真正重新分配url变量。 Also you are checking against 'True' which is a string, not a boolean value. 另外,您还要检查'True' ,它是一个字符串,而不是布尔值。 In addition I believe the offset should increase by the amount of results everytime; 另外,我认为抵消量应该每次都增加结果量。 not just one. 不只是一个 For example if on your first call you get results 1-25. 例如,如果在您的第​​一个电话中,您得到的结果是1-25。 Then if you increase y by one, the second call will yield 2-26. 然后,如果将y加1,则第二个调用将产生2-26。 Instead you should increase it by the limit. 相反,您应该将其增加限制。 This way on the second call you get results 25-50. 这样,在第二次通话中,您将获得25-50的结果。 Here is how I would do this: 这是我的处理方式:

def list_services():

    x = 25
    y = 0
    results = []
    serv_id = None
    flag = False

    url = f'https://api.pagerduty.com/services/?limit={x}&offset={y}'
    headers = {
        'Accept': 'application/vnd.pagerduty+json;version=2',
        'Authorization': 'Token token={token}'.format(token=API_KEY)
    }
    current_page = json.loads(requests.get(url, verify=False, headers=headers).content.decode('UTF-8'))
    results.append(current_page)

    for serv_set in current_page['services']:
            if serv_set['name'] == 'Networks':
                serv_id = serv_set['id']
                flag = True

    while current_page['more'] == True and not flag:
        for serv_set in current_page['services']:
            if serv_set['name'] == 'Networks':
                serv_id = serv_set['id']
                break
        y += x
        url = f'https://api.pagerduty.com/services/?limit={x}&offset={y}'
        current_page = json.loads(requests.get(url, verify=False, headers=headers).content.decode('UTF-8'))
        results.append(current_page)
        print(results) 
    print(results, serv_id) 

You could further clean this up to avoid some redundancy but this should work. 您可以进一步清理以避免某些冗余,但这应该可以工作。 You should also check the status of the API call to ensure that you have a valid response. 您还应该检查API调用的状态,以确保获得有效的响应。

Edit: 编辑:

I edited in the issue dealing with obtaining the id attribute when the name == 'Networks' . 我编辑了当name == 'Networks'时获取id属性的问题。 Once again you could reduce the redundancy in this a lot but this will get you on the right track. 再一次,您可以大量减少冗余,但这将使您步入正轨。 Now serv_id = the id of the service with the name of Networks . 现在serv_id =服务的ID,名称为Networks If no match is found at the end of the iterations then serv_id will be None . 如果在迭代结束时未找到匹配项,则serv_id将为None

while current_page['more'] == 'True':

You are checking for a string called 'True' instead of a boolean of True, as is defined in your json file. 您正在检查一个名为“ True”的字符串,而不是json文件中定义的True布尔值。 This could be why your while loop is never executing, and you are not receiving your print statement. 这可能就是为什么while循环永远不会执行,并且您没有收到打印语句的原因。

Also, generally for API calls that have more than 1 page of data, you need to specify which page you are getting. 此外,通常对于具有多于一页数据的API调用,您需要指定要获取的页面。 Which means you need to reinitialize your payload in your while loop. 这意味着您需要在while循环中重新初始化有效负载。

For example, if an API has a parameter called "page" that you can pass in, in your while loop you would have to pass in page = 1, page = 2, etc. as a payload. 例如,如果一个API具有可以传递的名为“ page”的参数,则在while循环中,您必须传递page = 1,page = 2等,以作为有效载荷。

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

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