如何在不使用gdata oauth2工作流的情况下授权gdata客户端?
我已经有了访问令牌(access_token)和刷新令牌(refresh_token),但是我不知道怎么才能创建一个经过授权的gdata客户端,而不需要重新走一遍生成令牌的整个流程。
3 个回答
-1
Gdata 让你可以用用户信息进行身份验证,比如用户名和密码。下面是来自 gdata python api 的一个代码片段,文件路径是 /gdata-2.0.18/samples/docs/docs_example.py。
class DocsSample(object):
"""DocsSample 对象演示了文档列表的功能。"""
def init(self, email, password):
"""DocsSample 对象的构造函数。
Takes an email and password corresponding to a gmail account to
demonstrate the functionality of the Document List feed.
Args:
email: [string] The e-mail address of the account to use for the sample.
password: [string] The password corresponding to the account specified by
the email parameter.
Returns:
A DocsSample object used to run the sample demonstrating the
functionality of the Document List feed.
"""
source = 'Document List Python Sample'
self.gd_client = gdata.docs.service.DocsService()
self.gd_client.ClientLogin(email, password, source=source)
# Setup a spreadsheets service for downloading spreadsheets
self.gs_client = gdata.spreadsheet.service.SpreadsheetsService()
self.gs_client.ClientLogin(email, password, source=source)
如果你用命令 {python ./docs_example.py --user username --pw password} 来运行这个程序,它会跳过询问你输入用户名和密码的步骤,但如果你不这样做,它就会问你。不过,这种方法正在被淘汰,但在大多数不直接与 Google 连接的网络环境中仍然有效,因为现在通常需要使用 oauth2。说到这里,它确实有一些安全隐患,特别是在权限范围和密码保护方面不够好,这就是它被淘汰的原因……不过这应该能更好地回答你的问题……
1
试试这个:
import httplib2
from oauth2client.client import OAuth2Credentials
credentials = OAuth2Credentials('access_token', client_id, client_secret, 'refresh_token', 'token_expiry','token_uri','user_agent')
# the client_id and client_secret are the ones that you receive which registering the App
# and the token_uri is the Redirect url you register with Google for handling the oauth redirection
# the token_expiry and the user_agent is the one that you receive when exchange the code for access_token
http = httplib2.Http()
http = credentials.authorize(http)
service = build('analytics', 'v3', http=http) # this will give you the service object which you can use for firing API calls
4
我终于把这个搞定了。下面是我怎么做到的:
client = gdata.contacts.client.ContactsClient()
credentials = gdata.gauth.OAuth2Token(client_id = 'client_id',
client_secret = 'client_secret',
scope = 'https://www.google.com/m8/feeds/',
user_agent = auth.user_agent, # This is from the headers sent to google when getting your access token (they don't return it)
access_token = auth.access_token,
refresh_token = auth.refresh_token)
credentials.authorize(client)
contacts = client.get_contacts()