In Python, how to correctly jump out of a While loop from Try?

2.4k views Asked by At

I am writing a Python function to send a GET request to a URL using user-submitted credentials and get a returned token for later use.

# Function for logging in and get a valid token
def getToken():
    while True: # Loop the cycle of logging in until valid token is received
        try:
            varUsername = raw_input("Enter your username: ")
            varPassword = getpass.getpass("Enter your password: ")
            reqAuthLogin = 'https://MY_URL?username=' + varUsername + '&password=' + varPassword # Send the login request
            varToken =  json.loads(urllib2.urlopen(reqAuthLogin).read())['Token'] # Attempt to parse the JSON response and read the Token, if possible
        except: # If credential is invalid and no token returned
            os.system('cls')
            print 'Invalid credentials. Please try again. \n'
        else: # I want this Try to exit the while loop if login is successful
            break

    os.system('cls')
    return varToken # Return the retrieved token at the end of this function

When the username/password combination is incorrect, the code throws a KeyError exception. I learned that Try-Else can break the innermost loop, in this case should be the while loop. In my design, I wanted the function to output the following message when an exception occurs (meaning invalid credentials):

Invalid credentials. Please try again.

Enter your username:

If the login is successful, the code is supposed to clear the screen and return the acquired token. The problem is, these code worked well when they were not in Try and not in While. Now it outputs this when the login is successful:

Enter your username:

Apparently the program does not execute the Else branch even though no exceptions occur. I am new to Python, please help me to identify the cause of this error.

EDIT: Thanks for the advice in comments. I set a few breakpoints, but the breakpoints showed that even if I insert a break at the end of try block, the program executes it first then directly go back to "while True" statement. It seemed like the break did not successfully exit the loop.

1

There are 1 answers

1
lucianopaz On BEST ANSWER

Why not just add a bool that is changed at the end of a successful try?

# Function for logging in and get a valid token
def getToken():
    gotToken = False
    while not gotToken: # Loop the cycle of logging in until valid token is received
        try:
            varUsername = raw_input("Enter your username: ")
            varPassword = getpass.getpass("Enter your password: ")
            reqAuthLogin = 'https://MY_URL?username=' + varUsername + '&password=' + varPassword # Send the login request
            varToken =  json.loads(urllib2.urlopen(reqAuthLogin).read())['Token'] # Attempt to parse the JSON response and read the Token, if possible
            gotToken = True
        except: # If credential is invalid and no token returned
            os.system('cls')
            print 'Invalid credentials. Please try again. \n'
    os.system('cls')
    return varToken # Return the retrieved token at the end of this function