我正在尝试使get_access_token函数仅执行一次,然后将令牌用于后续请求。但是,每次我调用令牌变量时,它似乎都在运行。请提供有关如何将令牌存储在变量中以及如何在必须调用或运行get_access_token函数的函数外部使用令牌的建议。
输出显示如下:
令牌是xxxxx
API1响应
令牌是yyyy
API2响应
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()
您可以将访问令牌保存在环境变量中。
env.access_token = public_api.get_access_token()
然后,通过访问环境变量而不是每次调用该函数将其附加在标题中
head = {"x-api-key": env.x_api_key, "token": env.access_token}