【字典取值】方式来保存token时第一次成功第二次失败了

你好,我使用你的接口自动化框架,我两次获取token并将token值保存下来,两次获取token都成功了,但是使用【字典取值】来保存token时第一次成功第二次失败了,麻烦您帮忙看看,我已经被这个问题困扰好几天了;谢谢,有偿解答

img

该回答引用ChatGPT
请参考下面的解决方案,如果有帮助,还请点击 “采纳” 感谢支持!

使用字典来存储token的方式可能不适用于多次请求,因为字典的内容在每次请求中是静态的。

一种解决方案是在请求前先检查字典中是否存在该token,如果存在则使用该token,如果不存在则请求新的token并保存到字典中。

还可以使用持久存储,例如文件或数据库,来保存token,以便在多次请求中使用。

此外,请注意token的生存期,有些token可能有限期,在过期后需要重新获取。

以下是使用字典来存储token的示例代码:

# Initialize the dictionary to store the token
tokens = {}

# Function to get the token
def get_token(token_name):
    # Check if the token already exists in the dictionary
    if token_name in tokens:
        return tokens[token_name]
    else:
        # Request for a new token
        response = requests.post(<token_url>, data=<request_data>)
        new_token = response.json()["token"]
        # Save the new token to the dictionary
        tokens[token_name] = new_token
        return new_token

# Use the get_token function to get the token
token = get_token("my_token")

以下是使用文件来存储token的示例代码


import os

# Get the path to the token file
token_file = os.path.join(os.path.dirname(__file__), "token.txt")

# Function to get the token
def get_token(token_name):
    # Check if the token file exists
    if os.path.exists(token_file):
        with open(token_file, "r") as f:
            return f.read()
    else:
        # Request for a new token
        response = requests.post(<token_url>, data=<request_data>)
        new_token = response.json()["token"]
        # Save the new token to the file
        with open(token_file, "w") as f:
            f.write(new_token)
        return new_token

# Use the get_token function to get the token
token = get_token("my_token")

我知道为啥了,各位大佬们,我没有加false
=False