[英]Why am I getting this error? (KeyError: 'username')
我向用戶詢問 email,然后將其發送到 email 驗證 api,然后我從中獲取某些信息。 我收到 KeyError: 'username' ,我不知道為什么會收到該錯誤。 測試也很煩人,因為它們在 ~5 次嘗試后會限制速率
import json, requests, sys
emailInput = ""
def printHelp():
print("Proper usage is: python test.py [email]")
if len(sys.argv) < 2:
printHelp()
sys.exit()
elif len(sys.argv) == 2 and sys.argv[1] == "--help":
printHelp()
sys.exit()
elif len(sys.argv) == 2 and sys.argv[1] != "--help":
emailInput = str(sys.argv[1])
url = 'https://api.trumail.io/v2/lookups/json?email=' + str(emailInput)
res = requests.get(url)
res.raise_for_status()
resultText = res.text
emailInfo = json.loads(resultText)
print("\nEmail Analyzer 1.0\n\nInformation for email: " + sys.argv[1])
print("=====================================================")
print("Username: " + str(emailInfo["username"]))
print("Domain: " + str(emailInfo["domain"]))
print("Valid Format: " + str(emailInfo["validFormat"]))
print("Deliverable: " + str(emailInfo["deliverable"]))
print("Full Inbox: " + str(emailInfo["fullInbox"]))
print("Host Exists: " + str(emailInfo["hostExists"]))
print("Catch All: " + str(emailInfo["catchAll"]))
print("Disposable: " + str(emailInfo["disposable"]))
print("Free: " + str(emailInfo["free"]))
原因是因為用戶輸入的 email 可能看起來有效 - 即它是帶有@
符號等的有效 email 地址 - 但 email 可能不存在或不存在。
例如,我使用以下虛擬輸入運行您的腳本:
emailInput = 'acdefg@gmail.com'
在我為調試目的添加了一個print(emailInfo)
語句后,我發現這是來自服務器的 output:
{'Message': 'No response received from mail server'}
因此,您的目標是驗證服務器輸入。 That is, in the case of a valid email that does not exist, you will receive an HTTP 200 (OK) response from the server with a Message
field alone populated the JSON response object. 此處的任務將是正確檢測此密鑰的存在,然后運行除上面已經處理的快樂路徑之外的單獨邏輯。
您的錯誤來自emailInfo
沒有密鑰username
的事實。 也許使用emailInfo.get("username", default_value)
,如果沒有用戶名, default_value 是您想要的任何值。
出現錯誤的行是print("Username: " + str(emailInfo["username"]))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.