I am making API call request for a list of IDs one by one and appending it to a Dict. Finally saving output as Json file. This code runs for more than 5 hours. Every 60 minutes the Bearer Token is getting expired. Is there a way where I can pause while loop every 60 minutes call the func() aagain to renew token and then pass the same inside header to continue the while loop. Or what is the best suggestion for this scenario. Please help.
import requests
import io
import hashlib
import time
import random
import json
from datetime import datetime, timezone
# -------------------- Generate Bearer Token ----------------------#
def myfun():
a = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
b = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
payload = {
'key_id': a,
'key_secret': b
}
response = requests.post('https://api.zdxcloud.net/v1/oauth/token',
headers={'Content-Type' : 'application/json', 'accept' : 'application/json'}, data=json.dumps(payload))
token = response.json()['token']
return "Bearer"+" "+token
accesstoken = myfun()
# -------------------- DeviceID to List ----------------------#
import pandas as pd
import json
xl = pd.read_json("D:Users.json")
deviceid = xl['id'].tolist()
# -------------------- Get Device Details ----------------------#
l = len(deviceid)
l = l-1
i = 0
id = deviceid[i]
st = datetime.now()
print(st)
data = {'mydata':[]}
while True:
id = deviceid[i]
url = "https://api.zdxcloud.net/v1/users/{0}".format(id)
payload={}
headers = {
'Accept': 'application/json',
'Authorization': accesstoken
}
response = requests.request("GET", url, headers=headers, proxies=proxies, data=payload)
results = response.json()
if i == 20000:
break
i = i + 1
data['mydata'].append(results)
json_object = json.dumps(data, indent=2)
with open("D:SysUserDetails.json", "w") as outfile:
outfile.write(json_object)
et = datetime.now()
print(et)
exit()
Vijay Kumar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.