最后我解决这样说:
- 安装新的App Engine服务帐户(我不知道,如果一个“新”之一是neccesary真的)
- 注意到,新的服务帐户电子邮件
- 与该服务帐户邮件共享表(我还没有测试过没有这一步)
- 将其服务机密作为JSON下载。
使用此代码(在启发(1)和(2))
class analysisHandler(Handler):
def get(self):
credentials = ServiceAccountCredentials.from_json_keyfile_name('service-secrets.json',
["https://www.googleapis.com/auth/spreadsheets"])
http = httplib2.Http()
#if credentials are still valid
if not credentials.invalid:
logging.info("Valid credentials, entering main function")
http = credentials.authorize(http)
main(http)
else:
credentials.refresh(http)
main(http)
然后在main():
sheetService = discovery.build('sheets', 'v4', http=authorized_http)
logging.info("Reading Google Sheet")
result = sheetService.spreadsheets().values().get(spreadsheetId=spreadsheet_id, range=range_name).execute(http=authorized_http)
urlfetch.set_default_fetch_deadline(45)
logging.info("Printing in Google Sheet")
sheetService.spreadsheets().values().append(spreadsheetId=spreadsheet_id, range="Log", body=body, valueInputOption="USER_ENTERED").execute(http=authorized_http)
凡authorized_http
参数是一个以前建造与credentials.authorize()
我认为这可以改善然而。
(1)How to use "Service account" authorization (rather than user based access refresh tokens)
(2)Creating and sharing Google Sheet spreadsheets using Python
但您确实意识到,通过这种方法,电子表格不再是“仅向公司成员公开”(因为它与外部实体共享),对吗? –
哦,是的,与服务帐户,谢谢指出。那可行。 – mclzc