2014-01-29 18 views
0

我知道這個標題是一個很大的混亂,我爲此道歉。我遇到的困境是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,你通常會。 噢!

回答

1

快速查看gspread指出它使用舊的ClientLogin身份驗證協議,該協議已被棄用。但是,你應該能夠從一個httplib2.Http()實例搶訪問令牌和應用相同的標題到gspread會話(有效地得到gspread到使用OAuth 2.0也):

http = <<<Your existing, authenticated httplib2.Http() object)>>> 
access_token = http.request.credentials.access_token 
gspread_auth_headers = {'Authorization': 'Bearer %s' % access_token} 
gspread_session = gspread.httpsession.HTTPSession(headers=gspread_auth_headers) 
my_gspread = gspread.Client(auth=('[email protected]', 'notmypassword'), http_session=gspread_session) 

[email protected]notmypassword是隨機的這裏只需要字符串,因爲gspread.Client希望auth是一個傳遞給它的元組,除非你調用my_gspread.login()(否則不會),否則它們不會傳遞給Google。

您將需要注意並捕獲過期的access_tokens。如果gspread拋出一個關於無效標記的錯誤,應該抓住它,調用http.request.credentials.refresh()來獲得一個新的訪問標記,然後用新標記重新創建gspread會話。

+0

我正在使用服務帳戶,這讓我懷疑是否會遇到過期的訪問令牌,因爲它使用密鑰對進行身份驗證。 (P.S. - 謝謝,我迫不及待想要試用!) –

+1

服務帳戶訪問令牌在1小時後過期,必須重新創建。查看https://developers.google.com/accounts/docs/OAuth2ServiceAccount#expiration代碼沒有經過測試,但理論上至少應該可以工作:-) –

+0

更新:我修復了我的客戶端上的gspread代碼,以實際*使用* 'Client'中的'http_session'參數。現在,它通過「AttributeError:'set'object has no attribute'items''」('File'/Library/Python/2.7/site-packages/gspread/httpsession.py',第59行,在請求中)。 –

相關問題