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.
JavaScript
x
12
12
1
class AccessToken:
2
def __init__(self):
3
self.token = get_new_access_token()
4
5
def new_token(self):
6
self.token = get_new_access_token()
7
print(self.token)
8
9
while True:
10
time.sleep(3600)
11
new_token()
12
JavaScript
1
8
1
def get_new_access_token():
2
body = {"client_id": config.ESPORT_ID,
3
"client_secret": config.ESPORT_SECRET_KEY_API
4
}
5
resp = requests.post(f'https://.........../oauth/token', json=body)
6
return resp
7
8
Advertisement
Answer
One way is to record when the token was made, and compare timestamp to see if token is valid.
JavaScript
1
23
23
1
class AccessToken:
2
TOKEN_TTL = 60 * 60 - 60 (`-60`: buffer)
3
4
def __init__(self):
5
self.new_token()
6
7
def refresh_token(self):
8
self.token = get_new_access_token()
9
self.token_gen_time = time.time() # When token was made
10
11
def get_token(self):
12
if time.time() > self.token_gen_time + self.TOKEN_TTL:
13
# token can be expired.
14
self.refresh_token()
15
return self.token
16
17
18
access_token = AccessToken()
19
while True:
20
time.sleep(5)
21
token = access_token.get_token()
22
# do something with token
23