2017-08-25 53 views
0

我試圖從Google Spreadsheet中讀取數據並向其寫入數據。我發現這個在線教程,這似乎爲很多人的工作:Google表格 - Python訪問超時

https://www.twilio.com/blog/2017/02/an-easy-way-to-read-and-write-to-a-google-spreadsheet-in-python.html?utm_source=youtube&utm_medium=video&utm_campaign=youtube_python_google_sheets

我做了什麼至今:

  • 根據指南創建的憑據並下載。 json文件
  • 與客戶電子郵件共享立法者電子表格(現在在我的谷歌驅動器)的副本。

  • 我分享後未收到郵件,因爲找不到服務帳戶域,我收到了一封電子郵件。

  • 我採用的代碼

    import gspread 
    from oauth2client.service_account import ServiceAccountCredentials 
    
    scope = ['https://spreadsheets.google.com/feeds'] 
    creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope) 
    client = gspread.authorize(creds) 
    
    sheet = client.open("Copy of Legislators 2017", scope) 
    list_of_hashes = sheet.get_all_records() 
    print(list_of_hashes) 
    

的client_secret.json文件是在同一文件夾中的項目。

enter image description here

但是當我運行的代碼,我收到以下錯誤:

enter image description here

日本說:「這是不可能的連接,因爲連接的被叫方沒有正確響應即使在一段時間之後。或連接的主機失敗,因爲連接的主機沒有響應。「

似乎有一個登錄問題,但我不知道如何解決它。 另外,雖然研究,我發現scope部分總是不同。有人可以向我解釋什麼需要插入嗎? 有沒有人有與它的經驗?感謝您的幫助:)

回答

0

確保您的OAuthclientID有效,並且您在Google開發者控制檯中啓用了Sheets API。

然後,嘗試使用Sheetsv4範圍。我記得我在使用v3的範圍時遇到了一些錯誤。所以希望這可以幫助你:

import gspread 
from oauth2client.service_account import ServiceAccountCredentials 
import pprint 

scope = ['https://www.googleapis.com/auth/spreadsheets'] 
creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope) 
client = gspread.authorize(creds) 

sheet = client.open('NAME_OF_GOOGLE_SHEET').sheet1 

pp = pprint.PrettyPrinter() 

# get all the records 
result = sheet.get_all_records() 

pp.pprint(result)