Python使用rest\u api(如果不是exis)创建项

2024-10-06 12:27:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个python脚本,它可以检查主机服务器上现有的令牌,如果找不到,它就会创建一个令牌。可能还有很多其他标记,但我只想忽略它们,只处理variable部分中指定的标记。你知道吗

下面的脚本能够找到一个现有的令牌,但是如果没有匹配项,则不会创建该令牌。我犯了什么错误?你知道吗

注意:如果执行create_token部分时没有while,那么条件也会应用于所有其他标记。但是我只想用我提供的变量值来限制循环。你知道吗

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

Tags: name标记tokenifaccessvaluecreateusername
1条回答
网友
1楼 · 发布于 2024-10-06 12:27:24

假设您想找出existing_tokens中是否有token['app']['name']与您的token_name匹配并创建一个,您可以这样做:

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

您的while token_value is token_name:实际上是while False,因为the ^{} operator checks that two variables refer to the same objecttoken_value可以是一个字符串,其值与token_name相同,但不能是同一个对象。你知道吗

但是,在for token in existing_tokens循环完成执行之前,您无法知道其他令牌是否与您想要的名称匹配,这就是为什么您必须按照上面所示重写逻辑的原因。你知道吗

相关问题 更多 >