'Build a timer function in Python, so a variable can be reused until x seconds has passed

this is more about logic. I am trying to build a timer function to create a bearer token with a TTL of 300 seconds. So re-use the variable with the token until time has passed.

But, I cannot see how to build a loop which does this. I have been using Python a few months now, and for first time I am really stuck. Am I overseeing some concept of counting and looping?:

How I managed the api-calls before: I wrote a .sh shell script which creates the bearer.json in a local directory on the server. It is automaticly refreshed every 290 seconds. This file is called every time when a requests.post() is made. But when these api-calls became +3/sec, I got random key-errors because the request was empty. After lots, lots of debugging, I learned this happened because when a shellscript is writing the new .json every 290s, the file is blocked for just a few miliseconds. When we make +30K api-calls in a row we get random errors. I tried to hack it with sleep to get the rate down, but this just spreads the random errors a bit wider over time. So now, I am trying to create the token-creating within Python itself.

What I did I created the token creation procedure, which works fine in itself.

import base64
import requests
import time
from datetime import datetime

client_id='demo-txt34538098045345'
client_secret='demo-txt3478975rgwerg'
combined_key_secret = client_id+":"+client_secret
based_combined_key_secret = base64.b64encode(combined_key_secret.encode()).decode()

headersAuth = {
    'Authorization': 'Basic '+ str(based_combined_key_secret),
}



## Authentication request

start_api_timer = time.time()

def getbearer(start_api_timer):
    # get starttime epoch
    #calculate time when bearer is expired: starttime +290 seconds
    end_api_timer = start_api_timer+290

    # response = requests.post('https://website.withapi/token?grant_type=client_credentials',headers=headersAuth)
    if  start_api_timer > end_api_timer:
        #j = response.json()
        j = "token is still valid"
        
    else:
       # response = requests.post('https://website.withapi/token?grant_type=client_credentials',headers=headersAuth)
        #j = response.json()
        j= "this is a new token"
        return j,start_api_timer,end_api_timer


x = getbearer(start_api_timer)
print(x)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source