簡體   English   中英

GMail API會隨機返回錯誤的錯誤

[英]GMail API returns unspeficied error at random moments

我正在Google App Engine上運行一個Python應用程序,該應用程序會定期檢查多個用戶的最新電子郵件。 我注意到,在隨機時刻,API返回以下錯誤:

error: An error occured while connecting to the server: Unable to fetch URL: https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest?userIp=0.1.0.2

通常,如果作業再次運行,它將正常工作。 在我的代碼下面。 我想了解是什么原因造成的,更重要的是,我如何才能防止錯誤阻止進程(例如,拋出此錯誤時如何使用相同的值再次運行作業)。

class getLatest(webapp2.RequestHandler):
  def post(self):
    try:
      email = self.request.get('email')
      g = Credentials.get_by_id(email)
      REFRESH_TOKEN = g.refresh_token
      start_history_id = g.hid

      credentials = OAuth2Credentials(None, settings.CLIENT_ID,
                             settings.CLIENT_SECRET, REFRESH_TOKEN, None,
                             GOOGLE_TOKEN_URI, None,
                             revoke_uri=GOOGLE_REVOKE_URI,
                             id_token=None,
                             token_response=None)

      http = credentials.authorize(httplib2.Http())
      service = discovery.build("gmail", "v1", http=http)
      for n in range(0, 5): 
        try:
          history = service.users().history().list(userId=email, startHistoryId=start_history_id).execute(http=http)
          break
        except errors.HttpError, e:
          if n < 4:
            time.sleep((2 ** n) + random.randint(0, 1000) / 1000)
          else:
            raise
      changes = history['history'] if 'history' in history else []
      while 'nextPageToken' in history:
        page_token = history['nextPageToken']
        for n in range(0, 5): 
          try:
            history = service.users().history().list(userId=email, startHistoryId=start_history_id, pageToken=page_token).execute(http=http)
            break
          except errors.HttpError, e:
            if n < 4:
              time.sleep((2 ** n) + random.randint(0, 1000) / 1000)
            else:
              raise
        changes.extend(history['history'])

    except errors.HttpError, error:
        logging.exception('An error occurred: '+str(error))
        if error.resp.status == 401:
            # Credentials have been revoked.
            # TODO: Redirect the user to the authorization URL.
            raise NotImplementedError()
        else:
            stacktrace = traceback.format_exc()
            logging.exception('%s', stacktrace)

UPDATE

我根據下面的答案更新了代碼,但是它似乎從未多次運行請求。 一旦發生異常,該過程就會中止。

造成此錯誤的原因有多種,其中包括您的代理暫時離線以超過Gmail API的速率限制。 如果出現這些臨時問題,您需要以適當的方式重試。 以下是可能有幫助的代碼編輯:

class getLatest(webapp2.RequestHandler):
  def post(self):

try:
  email = self.request.get('email')
  g = Credentials.get_by_id(email)
  REFRESH_TOKEN = g.refresh_token
  start_history_id = g.hid

  credentials = OAuth2Credentials(None, settings.CLIENT_ID,
                         settings.CLIENT_SECRET, REFRESH_TOKEN, None,
                         GOOGLE_TOKEN_URI, None,
                         revoke_uri=GOOGLE_REVOKE_URI,
                         id_token=None,
                         token_response=None)

  http = credentials.authorize(httplib2.Http())
  service = discovery.build("gmail", "v1", http=http)
  for n in range(0, 5):  
  try:
      history = service.users().history().list(userId=email, startHistoryId=start_history_id).execute(http=http)
      break
  except Exception as e:
        # Apply exponential backoff.
        time.sleep((2 ** n) + random.randint(0, 1000) / 1000)

  changes = history['history'] if 'history' in history else []
  while 'nextPageToken' in history:
    page_token = history['nextPageToken']

    for n in range(0, 5):  
    try:
       history = service.users().history().list(userId=email, startHistoryId=start_history_id, pageToken=page_token).execute(http=http)
       changes.extend(history['history'])
       break
    except Exception as e:
        # Apply exponential backoff.
        time.sleep((2 ** n) + random.randint(0, 1000) / 1000)
except errors.HttpError, error:
    logging.exception('An error occurred: '+str(error))
    if error.resp.status == 401:
        # Credentials have been revoked.
        # TODO: Redirect the user to the authorization URL.
        raise NotImplementedError()
    else:
        stacktrace = traceback.format_exc()
        logging.exception('%s', stacktrace)

從本質上講,如果在同一時間從指數點在Google端發生異常,此代碼將重試。 添加您要重試的錯誤代碼。 希望這能解決您的問題。

事實證明,這是與此處報告的問題相同的問題。 我遇到了請求發現文件的速率限制,您每天只需要這樣做一次。 我通過在我的應用中實施建議的解決方案來解決了這一問題。 可以在此Stackoverflow問題中找到代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM