我能够进行以下工作。它使用oauth2decorator来完成繁重的工作,然后使用一个小的帮助程序类TokenFromOAuth2Creds将这些相同的凭据应用到 gdata 客户端。
我应该先声明我不是 gdata 专家——可能有更好的方法来做到这一点——而且我还没有彻底测试过。
import webapp2
import httplib2
from oauth2client.appengine import oauth2decorator_from_clientsecrets
from apiclient.discovery import build
import gdata.contacts.client
decorator = oauth2decorator_from_clientsecrets(
  "client_secrets.json",
  scope=["https://www.google.com/m8/feeds", "https://www.googleapis.com/auth/calendar.readonly"]
)
# Helper class to add headers to gdata
class TokenFromOAuth2Creds:
  def __init__(self, creds):
    self.creds = creds
  def modify_request(self, req):
    if self.creds.access_token_expired or not self.creds.access_token:
      self.creds.refresh(httplib2.Http())
    self.creds.apply(req.headers)
class MainHandler(webapp2.RequestHandler):
  @decorator.oauth_required
  def get(self):
    # This object is all we need for google-api-python-client access
    http = decorator.http()
    # Create a gdata client
    gd_client = gdata.contacts.client.ContactsClient(source='<var>YOUR_APPLICATION_NAME</var>')
    # And tell it to use the same credentials
    gd_client.auth_token = TokenFromOAuth2Creds(decorator.get_credentials())
    # Use Contacts API with gdata library
    feed = gd_client.GetContacts()
    for i, entry in enumerate(feed.entry):
      self.response.write('\n%s %s' % (i+1, entry.name.full_name.text if entry.name else ''))
    # Use Calendar API with google-api-python-client
    service = build("calendar", "v3")
    result = service.calendarList().list().execute(http=http)
    self.response.write(repr(result))
app = webapp2.WSGIApplication([
  ("/", MainHandler),
  (decorator.callback_path, decorator.callback_handler()),
], debug=True)
请注意,如果您没有使用装饰器,并且通过其他方式获取了您的凭据对象,您可以通过以下方式创建相同的预授权 http 对象:
http = credentials.authorize(httplib2.Http())
使用 gdata 的另一种方法是直接使用http对象(由 返回decorator.http())-该对象将自动为您添加正确的授权标头-这可用于向任一 API 发出请求,但您需要处理制作请求和自己解析 XML/JSON:
class MainHandler(webapp2.RequestHandler):
  @decorator.oauth_required
  def get(self):
    http = decorator.http()
    self.response.write(http.request('https://www.google.com/m8/feeds/contacts/default/full')[1])    
    self.response.write(http.request('https://www.googleapis.com/calendar/v3/users/me/calendarList')[1])
httplib2 的文档:http:
 //httplib2.googlecode.com/hg/doc/html/libhttplib2.html#http-objects