chi*_*dog 5 python google-spreadsheet-api google-api-python-client
我正在尝试创建一个读取和写入谷歌电子表格的python脚本.我基本上已经在https://developers.google.com/sheets/quickstart/python上复制了python快速入门脚本,并使用https://developers.google.com/resources/api-libraries/documentation/上的参考进行了修改.sheets/v4/python/latest /.
使用快速入门脚本中显示的"get"方法,一切正常.我可以看到没有错误的表格.要使用"更新"而不是"获取"(写入工作表而不是读取它),我删除.readonly了范围网址的部分.我还get()使用update()包含编码的值的json对象替换方法并将其body作为参数包含在update()方法中json.dumps.这完全根据上面的第二个参考.
每次"无效数据"都会出现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()
Run Code Online (Sandbox Code Playgroud)
控制台错误:
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]]}"">
Run Code Online (Sandbox Code Playgroud)
小智 6
我也从API示例开始.以上有关为驱动器和表单启用两个API的信息帮助我解决了访问错误.
然后我发现.get(...).execute()返回一个对象,它是.update().execute()中输入所需的类型,它看起来像:
{u'range': u'Sheet1!A1:B2', u'values': [[u'cella1', u'cellb1'],
[u'cella2', u'cellb2']], u'majorDimension': u'ROWS'}
Run Code Online (Sandbox Code Playgroud)
在范围之间进行拟合,并将参数valueInputOption ='RAW'添加到.update()之后,我成功地使用以下代码片段写入了Google表格:
myBody = {u'range': u'Sheet1!A1:B2', u'values': [[u'Zellea1', u'Zelleb1'], [u'Zellea2', u'Zelleb2']], u'majorDimension': u'ROWS'}
rangeOutput = 'Sheet1!A1:B2'
res = spreadsheet.values().update( spreadsheetId=spreadsheetId, range=rangeOutput, valueInputOption='RAW', body=myBody ).execute()
Run Code Online (Sandbox Code Playgroud)
我发现body中包含的 argupdate()尽管在文档中显示为 json,但实际上需要是常规的 python 字典。我正在发送 json 格式的文本正文,我猜 google api 客户端正在寻找的是一个实际的 python dict 对象。