0

我正在尝试将传感器数据写入谷歌表格。大约一年前,我可以在同一张纸上写信,但我再次活跃在这个项目上,无法让它发挥作用。我相信 Oauth 已经改变,并且我已经更新了我的代码以进行更改。

在下面的代码中,我没有收到任何错误,但是在 GoogleSheet 中没有输入任何数据。此外,如果我查看 GoogleSheets,“上次打开”日期并不能反映我的程序将/应该写入该 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)
4

1 回答 1

0

我发现了我的问题。我已经更改了 3 件事以使 gspread 正常工作:

  1. 下载了一个新创建的json文件(可能不需要这一步)
  2. 在 chrome 中打开目标工作表后,我将其与 JSON 文件中的电子邮件地址“共享”。
  3. 在谷歌开发者控制台中,我启用了“Drive API”

但是,原始帖子中的代码不会刷新令牌。它将在 60 分钟后停止工作。

有效的代码(截至 2017 年 7 月)如下。代码写入名为“Datalogger”的谷歌工作表它写入谷歌视图中显示为 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)
于 2017-06-28T18:41:26.393 回答