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

问题描述 投票:0回答:1

这是我的代码:

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函数执行身份验证。然后我首先调用get来获取要导入的记录数,然后我使用线程来获取使用self.getdata函数的数据(页面)。当所有线程完成后,我返回结果。但这有效,令牌将在进程中间到期。

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

python python-requests
1个回答
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  ...

或者,如Klaus D.建议的那样,检查当前时间并在达到expires_in时刷新令牌。

© www.soinside.com 2019 - 2024. All rights reserved.