0

I am trying to write a python script that can check for an existing token on the host server and, if not found, it creates one. There could be many other tokens, but I just wanted to ignore them and process only the token specified in the variable section.

The script below is able to find an existing token, but if there is nothing matching, the token is not created. What mistake have I made?

Note: If I execute the create_token section without a while, the condition gets applied to all other tokens as well. But I wanted to restrict the loop with only the variable value I provided.

token_name = "example-1"

if __name__ == '__main__':
    existing_tokens = get_access_token(hostname, 'authorizations', username, userpass)
    #print(existing_tokens)
    if existing_tokens:   # Checking whether any token exists or not
        for token in existing_tokens:
            token_value = (token['app']['name'])
            if token_value == token_name:
                print("Token already exist!")
            else:
                while token_value is token_name:
                    create_token = post_access_token(hostname, 'authorizations', token_params, username, userpass)
                    print("Token Value: ", create_token['token'])
    else:
        create_token = post_access_token(hostname, 'authorizations', token_params, username, userpass)
        print("Token Value: ", create_token['token'])
Nickolay
  • 31,095
  • 13
  • 107
  • 185
Rio
  • 595
  • 1
  • 6
  • 27

1 Answers1

1

Assuming you wanted to find out if any of the existing_tokens have token['app']['name'] matching your token_name and create one otherwise, you could do something like this:

matching_token = next((token for token in existing_tokens 
                       if token['app']['name'] == token_name), None)
if matching_token is not None:
    print("Token already exist!")
else:
    create_token = post_access_token(hostname, 'authorizations', token_params, username, userpass)
    print("Token Value: ", create_token['token'])

Your while token_value is token_name: is effectively while False because the is operator checks that two variables refer to the same object, and token_value can be a string with the same value as token_name, but never the same object.

But also until the for token in existing_tokens loop finishes executing, you have no way of knowing if some other token matches the name you want, which is why you have to rewrite your logic as shown above.

Nickolay
  • 31,095
  • 13
  • 107
  • 185