如何在python中返回先前的(if语句)循环



我想写一个简单的函数(我是初学者),在我的脚本中,从VirusTotal检查和测试用户的API密钥。

这就是我的想法:

首先,我想检查用户是否在代码中输入他的API KEY或字段为空。

其次,我想检查API KEY是否正确。我不知道如何用最简单的方法检查它,所以我使用了我在VirusTotal上找到的最简单的查询,并检查响应代码是否为200。

但是当API密钥字段为空并且用户类型错误的API密钥时,我有问题。之后,我的功能就结束了。我想回到之前的if条件,并检查这次api密钥是否正确。

当用户输入正确的API KEY时,函数打印正确的消息。

这是我的代码:

import requests
import json
def auth_vt_apikey():
"""This function test VirusTotal's Api Key"""
api_key = ''
if api_key == '':
api_key = str(input("Please enter your VirusTotal's API Key: "))
else:
None
url = 'https://www.virustotal.com/vtapi/v2/url/report'
params = {'apikey': api_key}
response = requests.get(url, params=params)
if response.status_code == 200:
print('Your Api Key is correct')
else:
api_key = str(input("Your Api Key is incorrect. Please re-type your Api Key: "))

auth_vt_apikey()

你能给我解释一下我哪里做错了,还有什么值得补充的吗?我也将感谢链接到指南,这样我可以自学这个例子。

首先:函数内部的所有代码都需要缩进。

在请求API密钥的初始代码中:

api_key = ''
if api_key == '':
api_key = str(input("Please enter your VirusTotal's API Key: "))
else:
None

if api_key == ''是完全不必要的(它总是为真,因为你只是设置了api_key = ''),str()是围绕input()(它总是返回一个str)。只做:

api_key = input("Please enter your VirusTotal's API Key: ")

当您执行测试API密钥的请求时:

response = requests.get(url, params=params)
if response.status_code == 200:
print('Your Api Key is correct')
else:
api_key = str(input("Your Api Key is incorrect. Please re-type your Api Key: "))

你应该在一个循环中这样做,如果你想用新的键重新尝试:

while True:
response = requests.get(url, params={'apikey': api_key})
if response.status_code == 200:
print('Your Api Key is correct')
return api_key  # ends the loop and returns the valid key to the caller
api_key = input("Your Api Key is incorrect. Please re-type your Api Key: ")
# loop continues until the API key is correct

可以使用while循环,如下所示:

import requests
import json
def auth_vt_apikey():
"""This function test VirusTotal's Api Key"""
...

api_key = ''
api_key_valid = False
while (not api_key_valid):
if api_key == '':
api_key = str(input("Please enter your VirusTotal's API Key: "))
url = 'https://www.virustotal.com/vtapi/v2/url/report'
params = {'apikey': api_key}
response = requests.get(url, params={'apikey': api_key})
if response.status_code == 200:
print('Your Api Key is correct')
api_key_valid = True
else:
print("Your Api Key is incorrect.", end=" ")

auth_vt_apikey()

我认为你想达到这个目标:

import requests
import json
def auth_vt_apikey():
"""This function test VirusTotal's Api Key"""
url = 'https://www.virustotal.com/vtapi/v2/url/report'
api_key = ''
msg = "Please enter your VirusTotal's API Key: "
while api_key == '':
api_key = input(msg)
response = requests.get(url, params={'apikey': api_key})
if response.status_code == 200:
print('Your Api Key is correct')
else:
api_key = ''
msg = "Your Api Key is incorrect. Please re-type your Api Key: "

auth_vt_apikey()

最新更新