Skip to content
Advertisement

A class with a mutable variable. API token

I am trying to create an API client, but the problem is that the token changes every hour. I want to create a class that contains a “token” variable that should change every hour.

The idea is to get a token when first run the script, create this object and use it.

I have a function that successfully receives a new token on execution.

class AccessToken:
    def __init__(self):
        self.token = get_new_access_token()

    def new_token(self):
        self.token = get_new_access_token()
        print(self.token)

    while True:
        time.sleep(3600)
        new_token()
def get_new_access_token():
    body = {"client_id": config.ESPORT_ID,
            "client_secret": config.ESPORT_SECRET_KEY_API
    }
    resp = requests.post(f'https://.........../oauth/token', json=body)
    return resp 

Advertisement

Answer

One way is to record when the token was made, and compare timestamp to see if token is valid.

class AccessToken:
    TOKEN_TTL = 60 * 60 - 60 (`-60`: buffer)

    def __init__(self):
        self.new_token()

    def refresh_token(self):
        self.token = get_new_access_token()
        self.token_gen_time = time.time()  # When token was made

    def get_token(self):
        if time.time() > self.token_gen_time + self.TOKEN_TTL:
            # token can be expired.
            self.refresh_token()
        return self.token


access_token = AccessToken()
while True:
    time.sleep(5)
    token = access_token.get_token()
    # do something with token
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement