【发布时间】:2014-01-29 02:12:40
【问题描述】:
我知道这个标题很不靠谱,对此我深表歉意。我的困境是gspread 使用 Session 而Google APIs client library for Python 使用 HTTPLib2。我有一个与 Google API 客户端一起使用的服务帐户,并且想要获取经过身份验证的 httplib2.Http() 实例并将其包装,以便 gspread 可以像 Session 对象一样使用它。
更新:已修复 update 103 到 gspread。根据 Jay Lee 下面的精彩回答,以下是如何在 Python 2.7 中使用服务帐户初始化 gspread Client(您需要替换 /path/to/service-account.p12 并设置 sa_id):
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
from apiclient.discovery import build
# ...
with open('/path/to/service-account.p12') as f: sa_key = f.read()
credentials = SignedJwtAssertionCredentials(
sa_id, sa_key, 'https://spreadsheets.google.com/feeds')
http = httplib2.Http()
http = credentials.authorize(http)
build('drive', 'v2', http = http)
access_token = http.request.credentials.access_token
gspread_auth_headers = {'Authorization' : 'Bearer %s' % access_token}
gspread_session = gspread.httpsession.HTTPSession(headers=gspread_auth_headers)
fakeauth = ('notmyusername@gmail.com', 'notmypassword')
client = gspread.Client(fakeauth, http_session=gspread_session)
# https://github.com/burnash/gspread/issues/103
if False == hasattr(client, "session"):
client = gspread.Client(fakeauth)
client.session = gspread_session
现在您可以像往常一样使用client。 哇!
【问题讨论】:
标签: python session google-api-python-client gspread