lundi 18 mai 2020

How to get my get_access_token to run only once?

I am trying to get the get_access_token function to be executed only once and then use the token for subsequent requests. But it seems to be running every time I call the token variable. Please provide suggestions on how I can store the token in a variable and use it outside of the function woth having to call or run the get_access_token function.

The output prints like this:

token is xxxxx

API1 response

token is yyyy

API2 response

class api:

def get_access_token(token):
    url = env.base_url
    para = {"acctId": env.acct_id, "secret": env.secret_key}
    head = {"x-api-key": env.x_api_key}
    try:
        r = requests.get(url, params=para, headers=head)
        rf = json.dumps(r.json(), indent=4, sort_keys=True)
        dict = json.loads(rf)
        assert r.status_code == 200
        token = str(dict['token'])
        expires = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(dict['expireTime']))
        print('Token acquired successfully ' + token)
        return token
    except:
        print('Data error in access token')
        print(dict)

def get_driver_overview(self):
    url = env.base_url
    head = {"x-api-key": env.x_api_key, "token": public_api.get_access_token()}
    body = {"acctId": str(env.acct_id), "driverId": env.driver_id}
    try:
        r = requests.post(url, headers=head, json=body)
        rf = json.dumps(r.json(), indent=4, sort_keys=True)
        dict = json.loads(rf)
        assert r.status_code == 200
        print(dict)
    except:
        print("Error in driver_overview")
        print(dict)

def get_device_list(self):
    url = env.base_url
    head = {"x-api-key": env.x_api_key, "token": public_api.get_access_token()}
    body = {"acctId": str(env.acct_id)}
    try:
        r = requests.post(url, headers=head, json=body)
        rf = json.dumps(r.json(), indent=4, sort_keys=True)
        dict = json.loads(rf)
        assert r.status_code == 200
        print(dict)
    except:
        print("Error in device list api")
        print(dict)

public_api = api()
public_api.get_driver_overview()
public_api.get_device_list()

Aucun commentaire:

Enregistrer un commentaire