如何确保令牌在获取数据期间不会过期?

时间:2018-09-04 11:09:26

标签: python python-requests

这是我的代码:

data = {"client_id": config.client_id, "client_secret": config.client_secret,
        "grant_type": "client_credentials", "scope": "PublicApi"}


def kAuth(self, data):
    urlAuth = 'http://...'
    try:
        response = requests.post(urlAuth, data=data, verify=False)
        return response
    except requests.exceptions.HTTPError as err:
        print (err)
    except requests.exceptions.Timeout:
        pass
    except requests.exceptions.TooManyRedirects:
        pass
    except requests.exceptions.RequestException as e:
        print (e)
        sys.exit(1)

def kData(self, data, auth_token,...):

    hed = {'Authorization': 'Bearer ' + auth_token, 'Accept': 'application/json'}
    urlApi = 'http://...'.format(apifolder,additional)
    responsedata = requests.get(urlApi, data=data, headers=hed, verify=False)
    if responsedata.ok:
        num_of_records = int(math.ceil(responsedata.json()['total']))
        if num_of_records == 0:
            print ("No new records to import.")
            return None

        ...


        with ThreadPoolExecutor(max_workers=num_of_workers) as executor:
            futh = [(executor.submit(self.getdata, page, hed, data)) for page in pages]
            for data in as_completed(futh):
                datarALL.extend(data.result())
        print ("Finished generateing data.")
        return datarALL

def getdata(self, page, hed, data, ...):
   ...
   responsedata = requests.get(url, data=data, headers=hed, verify=False)
   return  ...

response = my_lib.kAuth(data)
if response.ok:
    access_token = response.json()['access_token']
    token_type = response.json()['token_type']
    expires_in = response.json()['expires_in']
    response_k = my_lib.kData(data, access_token, apifolder)

我首先使用kAuth函数执行身份验证。然后,我首先进行调用以获取要导入的记录数,然后使用线程通过self.getdata函数获取数据(页面)。当所有线程完成时,我返回结果。此方法有效,但是存在令牌将在流程中间到期的风险。

我的问题: 当前,代码仅在开始时进行一次身份验证,然后在auth_token中传递header并与之一起使用。如果令牌过期,如何修改令牌以刷新令牌?

1 个答案:

答案 0 :(得分:1)

我可能会很乐观,只是尝试一下请求。如果失败,则重新进行身份验证,然后重试该请求:

def getdata(self, page, hed, data, ...):
   ...
   responsedata = requests.get(url, data=data, headers=hed, verify=False)
   if responsedata.status_code == 401:
      hed['Authorization'] = 'Bearer ' + my_lib.kAuth(kauth_data).json()['access_token']
      responsedata = requests.get(url, data=data, headers=hed, verify=False)
   return  ...

或者,正如克劳斯·D(Klaus D.)建议的那样,检查当前时间并刷新令牌(如果已达到expires_in

)。