【发布时间】:2016-05-21 23:48:44
【问题描述】:
我正在尝试制作一个可以读取和写入谷歌电子表格的 python 脚本。我基本上复制了https://developers.google.com/sheets/quickstart/python 的python 快速启动脚本,并使用https://developers.google.com/resources/api-libraries/documentation/sheets/v4/python/latest/ 的参考对其进行了修改。
使用快速启动脚本中显示的“get”方法一切正常。我可以毫无错误地阅读工作表。要使用“更新”而不是“获取”(写入工作表而不是阅读),我删除了范围 URL 的 .readonly 部分。我还用update() 替换了get() 方法,并将body 作为参数包含在update() 方法中,其中包含用json.dumps 编码的值的json 对象。这都是根据上面的第二个参考。
对于“无效数据”,我每次都会收到 HttpError 400。
代码:
import httplib2
import os
import json
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'sheets.googleapis.com-python-quickstart.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def main():
"""Shows basic usage of the Sheets API.
Creates a Sheets API service object and prints the names and majors of
students in a sample spreadsheet:
https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
"""
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl)
spreadsheetId = '1Wbo5ilhw68IMUTSvnj_2yyRmWJ87NP-lHdJdaPBmTGA'
rangeName = 'Class Data!A2:E'
body = json.dumps({'values': [[0,0,0,0,0]]})
result = service.spreadsheets().values().update(
spreadsheetId=spreadsheetId, range=rangeName, body=body).execute()
if __name__ == '__main__':
main()
控制台错误:
Traceback (most recent call last):
File "/Users/user/Dropbox/python/jobs/test.py", line 73, in <module>
main()
File "/Users/user/Dropbox/python/jobs/test.py", line 69, in main
spreadsheetId=spreadsheetId, range=rangeName, body=body).execute()
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/oauth2client/util.py", line 135, in positional_wrapper
return wrapped(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/googleapiclient/http.py", line 832, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/1Wbo5ilhw68IMUTSvnj_2yyRmWJ87NP-lHdJdaPBmTGA/values/Class%20Data%21A2%3AE?alt=json returned "Invalid value at 'data' (type.googleapis.com/google.apps.sheets.v4.ValueRange), "{"values": [[0, 0, 0, 0, 0]]}"">
【问题讨论】:
-
您能否提供您在问题中尝试的代码而不是链接?
-
您使用的 .json 文件可能不是正确的,请提供控制台错误跟踪,它应该为我们指明正确的方向。
标签: python google-spreadsheet-api google-api-python-client