简体   繁体   中英

Why am I getting this error? (KeyError: 'username')

I'm asking the user for an email, and then sending it to an email verification api, which I then get certain bits of info from. I'm getting a KeyError: 'username' and I have no idea why I'm getting that error. It's also annoying to test since they ratelimit after ~5 attempts

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"]))

The reason is because a user enters an email that might seem valid - ie it's a valid email address with an @ symbol etc. - but the email likely does not exist or is not in use.

For example, I ran your script with the following dummy input:

emailInput = 'acdefg@gmail.com'

After I added a print(emailInfo) statement for debugging purposes, this is what I found to be the output from the server:

{'Message': 'No response received from mail server'}

Therefore, your goal here will be to validate the server input. 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. The task here will be to correctly detect the presence of this key, and then run a separate logic other than the happy path, which was already being handled above.

Your error is coming from the fact that emailInfo does not have a key username . Perhaps use emailInfo.get("username", default_value) , where default_value is any value you would like if there is no username.

The line with the error is print("Username: " + str(emailInfo["username"]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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