2015-09-25 48 views
0

我一直在試圖編寫一個python(IPython Notebook)腳本來訪問和處理Google表格數據。如何連接到Google表格而不與服務帳戶共享表單?

我已經查看了gspread(http://gspread.readthedocs.org/en/latest/oauth2.html),但所描述的流程要求將電子表格與註冊的Google服務帳戶(客戶端電子郵件)共享。這不起作用,因爲我的公司谷歌表不允許與「外部」帳戶共享。

但是似乎有一種方法,使接入(認證),如下所述:https://developers.google.com/drive/web/quickstart/python

但我無法弄清楚如何做到這一點在IPython的筆記本作爲示例代碼似乎需要命令行參數(我不明白)。

任何人都可以提供一些示例,瞭解如何使用服務帳戶訪問Google表格而不使用

回答

1

進一步搜索後,似乎這個問題已經在這裏找到答案: gspread/OAuth2: authenticated default gmail account (used early in ClientLogin) 解決的辦法是從: http://www.indjango.com/access-google-sheets-in-python-using-gspread/#comment-2026863410

這基本上只需要與谷歌創建一個Web應用程序客戶端編號。客戶端ID和密鑰可以用於認證流程如下:

from oauth2client.client import OAuth2WebServerFlow 
from oauth2client.tools import run 
from oauth2client.file import Storage 
CLIENT_ID = '<CLIENTID_FROM_GOOGLE_DEVLOPER_CONSOLE>' 
CLIENT_SECRET = '<CLIENTSECRET_FROM_GOOGLE_DEVLOPER_CONSOLE>' 
flow = OAuth2WebServerFlow(client_id=CLIENT_ID, 
          client_secret=CLIENT_SECRET, 
          scope='https://spreadsheets.google.com/feeds', 
          redirect_uri='http://localhost:8080/') 
storage = Storage('mycredentials.data') 
credentials = run(flow, storage) 
import requests 
import gspread, ast 
from oauth2client.client import AccessTokenCredentials 
data = { 
    'refresh_token' : credentials.refresh_token, 
    'client_id' : credentials.client_id, 
    'client_secret' : credentials.client_secret, 
    'grant_type' : 'refresh_token', 
} 
r = requests.post('https://accounts.google.com/o/oauth2/token', data = data) 
try : 
    credentials.access_token = ast.literal_eval(r.text)['access_token'] 
except Exception: 
    pass; 
gc = gspread.authorize(credentials) 

現在,gc應該很好用於gspread活動。這個流程需要兩個依賴:

pip install python-gflags oauth2client 

什麼我不知道的是,我得到了以下警告:

WARNING:root:This function, oauth2client.tools.run(), and the use of the gflags library are deprecated and will be removed in a future version of the library. 

不知道是什麼的了最新方式這樣做?

+0

根據https://github.com/pydata/pandas/issues/8327,我們只需要做'從oauth2client.tools導入run_flow,argparser'和'credentials = run_flow(flow,storage,argparser.parse_args( []))'代替run()調用以避免警告。 –