使用服务帐户从Google Appengine访问Google电子表格:每小时工作一次

时间:2016-03-18 10:23:17

标签: python-2.7 google-app-engine google-spreadsheet-api google-oauth2 service-accounts

我已根据文档在下面实现了python代码,以便访问可通过公共链接访问的电子表格。 它每小时工作一次。如果我在成功后几秒钟执行,我收到一个错误:

Error opening spreadsheet no element found: line 1, column 0

假设: 访问令牌的有效期为1小时。因此,一小时后,appengine将进行令牌刷新,重置整个。

问题: 此代码为每个请求请求一个新令牌。所以我该怎么做 ?保存令牌?当我尝试使用token_to_blob来保存令牌时,我收到一个错误:     范围未定义

提前感谢您的帮助!

    try :
        credentials = AppAssertionCredentials(scope=('https://www.googleapis.com/auth/drive','https://spreadsheets.google.com/feeds','https://docs.google.com/feeds'))
        logging.info("credentials")
        http_auth = credentials.authorize(httplib2.Http())
        authclient = build('oauth2','v2',http=http_auth)
        auth2token = gdata.gauth.OAuth2TokenFromCredentials(credentials)
    except Exception as details:
        logging.error("Error Google credentials %s"%details)
        return "Error"

    try :
        gd_client = gdata.spreadsheets.client.SpreadsheetsClient()
        gd_client = auth2token.authorize(gd_client)
        feed = gd_client.GetListFeed(<spreadsheetKey>,1)
    except Exception as details:
        logging.error("Error opening spreadsheet %s"%details)
        return "Error"

1 个答案:

答案 0 :(得分:1)

我终于宣布了凭据&amp;令牌为全局。 在这种情况下,它正在为几个后续请求工作,但在1小时后,令牌无效。

我使用access_token_expired方法进行了测试,但此方法始终返回false。

所以,我最终系统地执行了刷新,它的工作原理。不优雅但功能齐全。另一种选择是存储下次刷新的时间,并且仅在1小时后刷新。

欢迎您提出优雅的选择。

我没有尝试gspread,因为其余的代码已经可用于gdata.spreadsheets,但也许我应该。

from oauth2client.contrib.appengine import AppAssertionCredentials
from oauth2client.client import Credentials
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build
import httplib2

global credentials
global auth2token
try :
    credentials = AppAssertionCredentials(scope=('https://www.googleapis.com/auth/drive','https://spreadsheets.google.com/feeds','https://docs.google.com/feeds'))
    http_auth = credentials.authorize(httplib2.Http())
    authclient = build('oauth2','v2',http=http_auth)
    auth2token = gdata.gauth.OAuth2TokenFromCredentials(credentials)
except Exception as details:
    logging.error("Error Google credentials %s"%details)

class importFromSpreadsheet(webapp2.RequestHandler):
    def __importFromSpreadsheet(self,u):
        try :
            credentials._refresh(httplib2.Http())
        except Exception as details:
            logging.error("Error refreshing Google credentials %s"%details)
...
        try :
            gd_client = gdata.spreadsheets.client.SpreadsheetsClient()
            gd_client = auth2token.authorize(gd_client)
            feed = gd_client.GetListFeed(u,1)
        except Exception as details:
            logging.error("Error opening 1st spreadsheet %s"%details)
            return "Error"