【问题标题】:Accessing Google spreadsheet with Python for server-to-server use使用 Python 访问 Google 电子表格以供服务器到服务器使用
【发布时间】:2015-10-07 17:53:12
【问题描述】:

我正在尝试从某些目标用户每天都可以看到的服务器更新 Google 电子表格。这是我尝试过的:

在“console.developers.google.com”中创建一个项目,然后选择“驱动 API”->“凭据”->“添加凭据”->“服务帐户”->“创建 Json 文件”

现在有了这个 JSON 文件 (project name-e4sdfsdsdf0c.json),我尝试访问电子表格。

import gdata.spreadsheet.service
import gdata.service
import urlparse
import httplib2
from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client import tools
spreadsheet_key = '13jQtgSUXKBExMvZjECf6sdfsfgLfmRFVmZw6t7hYyX3g0'
storage = Storage("creds.dat")
credentials = storage.get() 
if credentials is None or credentials.invalid:
    credentials = tools.run_flow(flow_from_clientsecrets("project name-e4sdfsdsdf0c.json", scope=["https://spreadsheets.google.com/feeds"]), storage)
if credentials.access_token_expired:
    credentials.refresh(httplib2.Http())

spr_client = gdata.spreadsheet.service.SpreadsheetsService(
    additional_headers={'Authorization' : 'Bearer %s' % credentials.access_token})

worksheets = spr_client.GetSpreadsheetsFeed(spreadsheet_key)
print worksheets.title

但我收到此错误:

文件格式无效。请参阅https://developers.google.com/api-client-library/python/guide/aaa_client_secrets 需要一个 JSON 对象,该对象具有“网络”或“已安装”应用程序的单个属性”

【问题讨论】:

  • 决定使用 gspread + oauth2client。这要容易得多。

标签: python google-apps-script google-sheets server


【解决方案1】:

您创建了一个服务帐户,但您似乎正在尝试使用客户端流访问它。

在此处查看服务帐户文档: https://developers.google.com/identity/protocols/OAuth2ServiceAccount

第一步是返回开发者控制台并生成一个 p12 密钥。那么 Python 的基本流程是这样的:

from oauth2client.client import SignedJwtAssertionCredentials

scope = 'https://www.googleapis.com/auth/drive.readonly https://spreadsheets.google.com/feeds'

client_email = '<your service account email address>'
with open("MyProject.p12") as f:
  private_key = f.read()

credentials = SignedJwtAssertionCredentials(client_email, private_key, scope)
http_auth = credentials.authorize(Http())

【讨论】:

    【解决方案2】:

    Google Sheets API v4 在这里看起来非常简单。生成 json 文件后,您可以使用此代码访问电子表格。

    from oauth2client.service_account import ServiceAccountCredentials
    from httplib2 import Http
    from apiclient import discovery
    
    scopes = ['https://www.googleapis.com/auth/spreadsheets']
    credentials = ServiceAccountCredentials.from_json_keyfile_name(<path_to_your_client_secret.json>, scopes)
    http_auth = credentials.authorize(Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?version=v4')
    
    service = discovery.build('sheets', 'v4', http=http_auth, discoveryServiceUrl=discoveryUrl)
    result = service.spreadsheets().values().update(...).execute()
    

    【讨论】: