Skip to main content
 首页 » 编程设计

python之使用 Python 访问 Google 电子表格以供服务器到服务器使用

2025年05月04日14zhenyulu

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

在“console.developers.google.com”中创建一个项目,然后选择“drive API”->“credentials”->“add credentials”->“service accounts”->“create Json file”

现在有了这个 JSON 文件(项目名称-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 

但是我得到了这个错误:

Invalid file format. See https://developers.google.com/api-client-library/python/guide/aaa_client_secrets Expected a JSON object with a single property for a "web" or "installed" application"

请您参考如下方法:

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

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

第一步是返回开发人员控制台并生成一个 p12 key 。那么 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())