如何在迭代节点列表时返回bool



我有下面的代码,它做以下事情:

  • catalog_url获取所有节点(ip_addresss(的列表
  • 迭代节点列表,并为每个ip_address设置config_url
  • 获取每个ip_address的json数据,并检查json中是否有特定的东西,以及基于这些打印出来的东西

下面是我的方法:

def verify( config_url, catalog_url, config, action ):
flag = False
response = requests.get(catalog_url)
json_array = json.loads(response.content)
for x in json_array:
ip = x['IPAddress']
# get data for each ip_address
response = requests.get(config_url.format(ip))
data = json.loads(response.content)
# check data for each ip_address
if(action == 'push' and data['latestCfg'] == config):
print(ip + " downloaded successfully")
elif(action == 'check' and data['procCfg'] == config):
print(ip + " verified successfully")

问题陈述

现在我需要从上面的方法返回一个布尔值。如果任何一台机器未能成功下载或验证,那么我需要返回false,否则我将从上述方法返回true。我对如何用我目前的设置在上面的方法中做到这一点感到困惑?

使用&或booelan运算符and,如果任何操作数是False,则可以获得False

>>> True & True
True
>>> True & False
False
# or using `and`
>>> True and True
True
>>> True and False
False
  • True标志开始
  • 使用&=累加标志
def verify(config_url, catalog_url, config, action):
flag = True
response = requests.get(catalog_url)
json_array = response.json()
for x in json_array:
...
if action == 'push':
flag &= data['latestCfg'] == config
elif action == 'check':
flag &= data['procCfg'] == config
# If you want to stop as soon as operation fail
# if not flag:
#     break
return flag

旁注:您可以用response.json()替换json.loads(response.content)

您可以在进入循环之前将标志设置为True。如果下载或检查失败,可以将Flag设置为False。最后返回Flag。

诀窍是在进入循环之前将Flag设置为True。然后在遇到故障时将Flag翻转为False。如果您将标志设置为False一次,那么即使所有其他项都成功,它在循环的其余部分也将保持False。这样你就知道你有一个失败了。如果你想跳出循环并返回,那么一定要返回False。这将打破循环并返回False。

以下是您的操作方法。

def verify( config_url, catalog_url, config, action ):
flag = True #set to True and flip to False inside the loop when if statement fails
response = requests.get(catalog_url)
json_array = json.loads(response.content)
for x in json_array:
ip = x['IPAddress']
# get data for each ip_address
response = requests.get(config_url.format(ip))
data = json.loads(response.content)
# check data for each ip_address
if(action == 'push' and data['latestCfg'] == config):
print(ip + " downloaded successfully")
elif(action == 'check' and data['procCfg'] == config):
print(ip + " verified successfully")
else:
flag = False #set to False if above two if statements fail
return flag #if flag got set to False even once, it will return False, else it will return True

可能是这样的?

def verify( config_url, catalog_url, config, action ):
flag = True
response = requests.get(catalog_url)
json_array = json.loads(response.content)
for x in json_array:
ip = x['IPAddress']
# get data for each ip_address
response = requests.get(config_url.format(ip))
data = json.loads(response.content)
# check data for each ip_address
if action == 'push':
if data['latestCfg'] == config:
print(ip + " downloaded successfully")
else:
flag = False
elif action == 'check':
if data['procCfg'] == config:
print(ip + " verified successfully")
else:
flag = False
return flag

最新更新