2017-06-28 55 views
0

我正在嘗試將傳感器數據寫入Google工作表。我能夠在一年前寫了同一張表,但我再次活躍在這個項目上,無法使其工作。我相信Oauth已經改變了,並且我已經更新了我的代碼以適應這種變化。gspread數據不會出現在Google工作表中

在下面的代碼中,我沒有收到任何錯誤,但沒有在GoogleSheet中輸入數據。另外,如果我查看Google表格,「上次打開」日期並不反映我的程序將/應該寫入該Google表格的時間。 我試過很多變化,我只是卡住了。任何建議,將不勝感激。

#!/usr/bin/python3 
#-- developed with Python 3.4.2 
# External Resources 
import time 
import sys 
import json 
import gspread 
from oauth2client.service_account import ServiceAccountCredentials 
import traceback 
# Initialize gspread 
scope = ['https://spreadsheets.google.com/feeds'] 
credentials = ServiceAccountCredentials.from_json_keyfile_name('MyGoogleCode.json',scope) 
client = gspread.authorize(credentials) 

# Start loop ________________________________________________________________ 
samplecount = 1 
while True: 
    data_time = (time.strftime("%Y-%m-%d %H:%M:%S")) 
    row = ([samplecount,data_time]) 

    # Append to Google sheet_ 
    try: 
     if credentials is None or credentials.invalid: 
      credentials.refresh(httplib2.Http()) 
     GoogleDataFile = client.open('DataLogger') 
     #wks = GoogleDataFile.get_worksheet(1) 
     wks = GoogleDataFile.get_worksheet(1) 
     wks.append_row([samplecount,data_time]) 
     print("worksheets", GoogleDataFile.worksheets()) #prints ID for both sheets 
    except Exception as e: 
     traceback.print_exc() 
    print ("samplecount ", samplecount, row) 
    samplecount += 1 
    time.sleep(5) 

回答

0

我發現我的問題。我已經改變了三件事得到gspread工作:

  1. 下載一個新創建的JSON文件(可能並不需要這一步)
  2. 與目標工作表在Chrome中打開,我「共享」其與電子郵件地址在JSON文件中找到。
  3. 在谷歌開發者控制檯,我啓用了「驅動器API」

然而,在原來的職位代碼將無法刷新令牌。它會在60分鐘後停止工作。

有效的代碼(截至2017年7月)如下。 該代碼寫入名爲「Datalogger」的谷歌表格 它在Google視圖中寫入Sheet2顯示的工作表。 唯一的唯一信息是JSON文件的名稱

希望這有助於他人。

喬恩

#!/usr/bin/python3 
# -- developed with Python 3.4.2 
# 
# External Resources __________________________________________________________ 
import time 
import json 
import gspread 
from oauth2client.service_account import ServiceAccountCredentials 
import traceback 

# Initialize gspread credentials 
scope = ['https://spreadsheets.google.com/feeds'] 
credentials = ServiceAccountCredentials.from_json_keyfile_name('MyjsonFile.json',scope) 
headers = gspread.httpsession.HTTPSession(headers={'Connection': 'Keep-Alive'}) 
client = gspread.Client(auth=credentials, http_session=headers) 
client.login() 
workbook = client.open("DataLogger") 
wksheet = workbook.get_worksheet(1) 

# Start loop ________________________________________________________________ 
samplecount = 1 
while True: 
    data_time = (time.strftime("%Y-%m-%d %H:%M:%S")) 
    row_data = [samplecount,data_time] 
    if credentials.access_token_expired: 
     client.login()   
    wksheet.append_row(row_data) 
    print("Number of rows in out worksheet ",wksheet.row_count) 
    print ("samplecount ", samplecount, row_data) 
    print() 
    samplecount += 1 
    time.sleep(16*60) 
相關問題