2017-06-28 50 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)