進一步搜索後,似乎這個問題已經在這裏找到答案: 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.
不知道是什麼的了最新方式這樣做?
根據https://github.com/pydata/pandas/issues/8327,我們只需要做'從oauth2client.tools導入run_flow,argparser'和'credentials = run_flow(flow,storage,argparser.parse_args( []))'代替run()調用以避免警告。 –