1

我正在尝试将 Google Docs API 与 Python+Django 和 OAuth 2 一起使用。我通过 google-api-python-client 获得了 OAuth 访问令牌等,代码基本上是从http://code 复制的。 google.com/p/google-api-python-client/source/browse/samples/django_sample/plus/views.py

现在,我假设我应该使用 google gdata API,v 2.0.17。如果是这样,我无法准确找到如何授权使用 gdata 客户端进行的查询。http://packages.python.org/gdata/docs/auth.html#upgrading-to-an-access-token上的文档(无论如何都显得过时了),说将客户端上的 auth_token 属性设置为gdata.oauth.OAuthToken。如果是这种情况,我应该将哪些参数传递给 OAuthToken?

简而言之,我正在寻找一个简短的示例,说明如何在给定 OAuth 访问令牌的情况下授权使用 gdata API 进行的查询。

4

2 回答 2

5

OAuth 2.0 序列类似于以下内容(给定为您注册的应用程序适当定义的应用程序常量)。

  1. 生成请求令牌。

    token = gdata.gauth.OAuth2Token(client_id=CLIENT_ID, 
                                    client_secret=CLIENT_SECRET, 
                                    scope=" ".join(SCOPES), 
                                    user_agent=USER_AGENT)
    
  2. 授权请求令牌。对于一个简单的命令行应用程序,您可以执行以下操作:

    print 'Visit the following URL in your browser to authorise this app:'
    print str(token.generate_authorize_url(redirect_url=REDIRECT_URI))
    print 'After agreeing to authorise the app, copy the verification code from the browser.'
    access_code = raw_input('Please enter the verification code: ')
    
  3. 获取访问令牌。

    token.get_access_token(access_code)
    
  4. 创建一个 gdata 客户端。

    client = gdata.docs.client.DocsClient(source=APP_NAME)
    
  5. 授权客户。

    client = token.authorize(client)
    

您可以通过执行以下操作保存访问令牌以供以后使用(因此避免在令牌再次过期之前执行手动身份验证步骤):

f = open(tokenfile, 'w')
blob = gdata.gauth.token_to_blob(token)
f.write(blob)
f.close()

下次开始时,您可以通过执行以下操作重用保存的令牌:

f = open(tokenfile, 'r')
blob = f.read()
f.close()
if blob:
    token = gdata.gauth.token_from_blob(blob)

然后,对身份验证序列的唯一更改是您通过指定 refresh_token 参数将此令牌传递给 OAuth2Token:

token = gdata.gauth.OAuth2Token(client_id=CLIENT_ID, 
                                client_secret=CLIENT_SECRET, 
                                scope=" ".join(SCOPES), 
                                user_agent=USER_AGENT,
                                refresh_token=token.refresh_token)

希望这可以帮助。花了一段时间来解决它:-)。

于 2012-06-06T16:48:26.453 回答
0

这是来自https://developers.google.com/gdata/docs/auth/overview

警告:大多数较新的 Google API 不是 Google Data API。Google 数据 API 文档仅适用于 Google 数据 API 目录中列出的旧 API。有关特定新 API 的信息,请参阅该 API 的文档。有关使用较新 API 授权请求的信息,请参阅 Google 帐户身份验证和授权。

您应该使用 OAuth 进行授权和访问,或者同时使用 OAuth 2.0。

对于 OAuth 2.0 API,现在位于https://developers.google.com/gdata/docs/directory

于 2012-06-06T13:24:31.463 回答