我想在我的腳本中撰寫一個簡單的函式(我是初學者)來檢查和測驗來自 VirusTotal 的用戶 API 密鑰。
那是我的想法:
首先,我想檢查用戶是否在代碼或欄位中鍵入他的 API KEY 為空。
其次,我想檢查 API KEY 是否正確。我不知道如何以最簡單的方式檢查它,所以我使用我在 VirusTotal 上找到的最簡單的查詢并檢查回應代碼是否為 200。
但是當 API 密鑰欄位為空并且用戶輸入錯誤的 API 密鑰時,我遇到了問題。之后,我的功能結束。我想回到之前的 if 條件,檢查這次 api key 是否正確。
當用戶輸入正確的 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()
您能向我解釋一下我在這里做錯了什么以及值得補充的地方嗎?我也將感謝指南的鏈接,這樣我就可以在這個例子中自學。
uj5u.com熱心網友回復:
我想你想實作這個:
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 = str(input(msg))
params = {'apikey': api_key}
response = requests.get(url, params=params)
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()
uj5u.com熱心網友回復:
您可以使用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()
uj5u.com熱心網友回復:
首先:所有應該在你的函式中的代碼都需要縮進。
在請求 API 密鑰的初始代碼中:
api_key = ''
if api_key == '':
api_key = str(input("Please enter your VirusTotal's API Key: "))
else:
None
theif api_key == ''是完全沒有必要的(它永遠是真的,因為你剛剛設定api_key = ''了),str()around也是如此input()(它總是回傳 a 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/534453.html
