我知道這個標題是一個很大的混亂,我爲此道歉。我遇到的困境是gspread使用Session,而Google APIs client library for Python使用HTTPLib2。我有一個服務帳戶,我已經與Google API客戶端合作並希望獲取已認證的httplib2.Http()
實例並將其包裝,以便gspread可以像Session對象一樣使用它。如何將HTTPLib2實例轉換/包裝爲Session?
更新:修復與update 103 gspread。基於以下週杰倫李的真棒答案,這裏是如何使用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 = ('[email protected]', '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
,你通常會。 噢!
我正在使用服務帳戶,這讓我懷疑是否會遇到過期的訪問令牌,因爲它使用密鑰對進行身份驗證。 (P.S. - 謝謝,我迫不及待想要試用!) –
服務帳戶訪問令牌在1小時後過期,必須重新創建。查看https://developers.google.com/accounts/docs/OAuth2ServiceAccount#expiration代碼沒有經過測試,但理論上至少應該可以工作:-) –
更新:我修復了我的客戶端上的gspread代碼,以實際*使用* 'Client'中的'http_session'參數。現在,它通過「AttributeError:'set'object has no attribute'items''」('File'/Library/Python/2.7/site-packages/gspread/httpsession.py',第59行,在請求中)。 –