【问题标题】:gspread w/ OAuth2Client Service Account Keygspread w/ OAuth2Client 服务帐户密钥
【发布时间】:2016-08-10 17:43:48
【问题描述】:

我正在使用 gspread 和服务帐户密钥、其他、json 文件。使用 python 2.7 不断更新谷歌电子表格。我有一个运行最新的 Raspian Jessie 的 Raspberry Pi。我的 oauth 和 gspread 都应该是适用于我的平台的最新版本。我的脚本运行一小时(最大令牌寿命),然后停止使用错误消息:“无效令牌:无状态令牌过期错误”我的代码如下

import gspread
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
from httplib2 import Http

scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(filename.json,scope)
gc = gspread.authorize(credentials)
wks = gc.open('spreadsheet name')
p1 = wks.worksheet('Printer One')

def functon()
...
p1.append_row(printing)

任何帮助将不胜感激,谢谢。

【问题讨论】:

    标签: python-2.7 google-oauth gspread


    【解决方案1】:

    授权每 0.5/1 小时到期一次(我认为这取决于您使用的两种可用连接方法中的哪一种)。

    我有一个 24/7 全天候连接的谷歌表格,每 2 秒更新一次。 几乎读取/写入错误的原因总是授权错误,但 Google API 也会向您抛出各种错误,这些错误通常会在几秒钟后解决。这是我更新单元格的功能之一,但使用auth_for_worksheet 的详细信息。每个操作(更新单个单元格、更新范围、读取一列值)都有一些类似的构造作为函数,它总是返回一个授权的工作表。这可能不是最优雅的解决方案,但该表已经连接了 3 个月,没有停机。

    def auth_for_worksheet():
        scope = ['https://spreadsheets.google.com/feeds']
        credentials = ServiceAccountCredentials.from_json_keyfile_name(filename.json,scope)
        gc = gspread.authorize(credentials)
        wks = gc.open('spreadsheet name')
        p1 = wks.worksheet('Printer One')
        return p1
    
    def update_single_cell(worksheet, counter, message):
        """ No data to return, update a single cell in column B to reflect this """
    
        single_cell_updated = False
        while not single_cell_updated:
            try:
                cell_location = "B" + str(counter)
                worksheet.update_acell(cell_location, message)
                single_cell_updated = True
            except gspread.exceptions.HTTPError:
                logger.critical("Could not update single cell")
                time.sleep(10)
                worksheet = auth_for_worksheet()
        logger.info("Updated single cell")
        return worksheet
    
    if __name__ == '__main__':
    
        # your code here, but now to update a single cell
        wksheet = update_single_cell(wksheet, x, "NOT FOUND")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-07
      • 2016-06-26
      • 1970-01-01
      • 2021-11-24
      • 2018-06-30
      相关资源
      最近更新 更多