简体   繁体   中英

Gmail API on GAE: Correctly using discovery.build_from_document()

I'm running a number of tasks on the GMail API and am getting the same error as described in this issue . To resolve it, I would like to implement the suggested solution. However I am not sure how to apply this to my code.

My code currently looks as follows:

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)

Now I am supposed to run following code at some moment in time:

resp, content = h.request('https://www.googleapis.com/discovery/v1/apis/analytics/v3/rest?quotaUser=the_name_of_your_app_goes_here')

And then save the value for content in the datastore. The issue explains this is not user-bound, however it is not clear to me if I should run this once and store the value until eternity, or refresh it at certain moments in time.

In addition, since I am handling authorization a bit different, I have the feeling I will run into issues there as well if I implement it the exact same way. Cause when I build the service, I actually add the credentials in the call:

http = credentials.authorize(httplib2.Http())
service = discovery.build("gmail", "v1", http=http)

Turns out it was quite straight forward. I added following function:

def get_discovery_content():
  content = memcache.get('gmail_discovery')
  if content is not None:
    return content
  else:
    h = httplib2.Http()
    for n in range(0, 5):
      resp, content = h.request('https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest?quotaUser=replimeapp')
      if resp.status == 200:
        memcache.add('gmail_discovery', content, 86400)
        return content  

Then I replaced this line:

service = discovery.build("gmail", "v1", http=http)

By this:

content = get_discovery_content()
service = discovery.build_from_document(content)

Works like a charm so far.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM