我正在尝试将 Google Docs API 与 Python+Django 和 OAuth 2 一起使用。我通过 google-api-python-client 获得了 OAuth 访问 token 等,代码基本上是从 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 访问 token 的情况下授权使用 gdata API 进行的查询。
最佳答案
OAuth 2.0 序列类似于以下内容(为您注册的应用程序提供适当定义的应用程序常量)。
生成请求 token 。
token = gdata.gauth.OAuth2Token(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope=" ".join(SCOPES), user_agent=USER_AGENT)
授权请求 token 。对于简单的命令行应用程序,您可以执行以下操作:
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: ')
获取访问 token 。
token.get_access_token(access_code)
创建 gdata 客户端。
client = gdata.docs.client.DocsClient(source=APP_NAME)
授权客户端。
client = token.authorize(client)
您可以保存访问 token 供以后使用(这样就避免了在 token 再次过期之前必须执行手动身份验证步骤),方法是:
f = open(tokenfile, 'w')
blob = gdata.gauth.token_to_blob(token)
f.write(blob)
f.close()
下次开始时,您可以通过执行以下操作重用保存的 token :
f = open(tokenfile, 'r')
blob = f.read()
f.close()
if blob:
token = gdata.gauth.token_from_blob(blob)
然后,对身份验证序列的唯一更改是您通过指定 refresh_token 参数将此 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)
希望这对您有所帮助。花了一些时间才弄明白 :-)。
关于python - 使用 Google Docs List API、Python 和 OAuth 2 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10907087/