我正在用Python编写一个应用程序,该应用程序可以从Google表格中读取数据,但我也希望能够以编程方式添加命名范围,以减少非常繁琐且易于出错的输入。除单元格B1中的值foo
之外,该工作表为空。读取部分可以正常工作,如本示例中所示,但是在尝试编写时,我得到了401,未授权。尽管事实上我正在使用https://developers.google.com/sheets/api/guides/authorizing
https://www.googleapis.com/auth/spreadsheets
为了编写范围,我使用了https://developers.google.com/sheets/api/samples/ranges
中的示例代码整个程序如下:
from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import requests
# Setup the Sheets API
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))
# Specific spreadsheet, actual ID hidden in this example
SPREADSHEET_ID = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
# Utility functions
def add_named_range():
url = 'https://sheets.googleapis.com/v4/spreadsheets/%s:batchUpdate'%SPREADSHEET_ID
data = '''{
"requests": [
{
"addNamedRange": {
"namedRange": {
"name": "test",
"range": {
"sheetId": "%s",
"startRowIndex": 1,
"endRowIndex": 1,
"startColumnIndex": 1,
"endColumnIndex": 1,
},
}
}
}
]
}
'''%SPREADSHEET_ID
response = requests.post(url, data=data)
return response
def get_value_from_range(range_name, spreadsheetId=SPREADSHEET_ID):
result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID,
range=range_name).execute()
if not 'values' in result.keys():
return None
else:
return result['values'][0][0]
print(get_value_from_range('data'))
res = add_named_range()
print(res.text)
,运行时的打印输出为
foo
{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
因此该程序能够读取数据,但不能写入,因此要添加一个命名范围。我在这里做什么错了?