使用令牌身份验证发送多个请求?

时间:2018-05-23 17:57:32

标签: python pandas api dataframe python-requests

目前我的API需要使用令牌身份验证。

POST /api/authorize HTTP/1.1

"version": "20151130", // The version of the REST API you are using
"client_id": "01234567890123456789", // Your 20 char public client id
"client_secret": "0123456789..." // Your 40 char client secret

我收到回复:

{
  "auth_token": "abcdef...",
  "auth_expires": "20180524T062442Z"
}

我目前的模式是这样的:

我有一个items的列表,我需要通过POST方法传递给API。 这是我的主要功能:ProcessProducts接收一个Pandas Dataframe,每行包含一个产品。

def ProcessProducts(products):
   all_results = []
   for _, product in products.iterrows():
     results = GetProductData(product)
     if results:
        all_results.extend(results)
   return all_results


def GetAuthorizationToken():
    payload = {
        'version': api_version,
        'client_id': api_client_id,
        'client_secret': api_client_secret
    }

    request_url = '%s%s' % (api_host, '/api/authorize')
    r = requests.post(request_url, data=payload)

    if r.status_code != 200:
        raise Exception('Failed to authorize: ' + r.text)

    token_data = json.loads(r.text)
    api_auth_token = token_data['auth_token']
    api_auth_expires = token_data['auth_expires']

    return {
        "X-API-Version": api_version,
        "Authorization": "token %s" % api_auth_token
    }

客户端功能......

def GetProductData(self, product):
    """Gets Product information from API."""

    url = '%s%s' % (self.api_url, _COMPANY_DATA)
    request = json.dumps({'products': [product]})
    form_data = {'request': request, 'start': 1, 'limit': 1000}
    logging.info('Looking up: %s', url)
    auth_headers = GetAuthorizationToken()
    response = _SendApiRequest(url, auth_headers, form_data)
    return _HandleResponse(response)


def _SendApiRequest(self, url, auth_headers, form_data):
    session = requests.Session()
    try:
      response = session.post(
          url,
          timeout=(_CONNECT_TIMEOUT_SECONDS, _READ_TIMEOUT_SECONDS),
          headers=auth_headers,
          data=form_data,
          verify=True)  # Check for valid public/signed HTTPS certificate.
      response.raise_for_status()
      return response
    except requests.exceptions.HTTPError as err:
      logging.exception(err)

问题:

  • API返回代码到期字段" auth_expires",哪里可能是令牌过期时检入代码的最佳方式,以便我可以请求新的?

  • 是否有更好的模式来调用API,因此我也可以控制QPS速率(使用RateLimiter)。现在我正在为每个请求创建一个会话,这可能并不理想。

0 个答案:

没有答案
相关问题