【发布时间】:2018-08-09 16:34:55
【问题描述】:
我无法通过 python 将数据写入谷歌表格。我在 Google Sheets Api 示例中做了所有的事情,但它仍然不起作用。这是我的项目:
from __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file as oauth_file, client, tools
SCOPES = ['https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file']
SAMPLE_SPREADSHEET_ID = 'ID'
SAMPLE_RANGE = 'Sheet2!A1:A10'
def main():
store = oauth_file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))
values = {'values': [['one','two','three']]}
result = service.spreadsheets().values().append(
spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE,
valueInputOption='RAW',
body=values).execute()
print('{0} cells updated.'.format(result.get('updatedCells')));
if __name__ == '__main__':
main()
它给了我这个错误:
C:\Users\Victor\Anaconda3\python.exe "C:/Users/Victor/Desktop/NEW try/try1.py"
Traceback (most recent call last):
File "C:/Users/Victor/Desktop/NEW try/try1.py", line 31, in <module>
main()
File "C:/Users/Victor/Desktop/NEW try/try1.py", line 27, in main
body=values).execute()
File "C:\Users\Victor\Anaconda3\lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Users\Victor\Anaconda3\lib\site-packages\googleapiclient\http.py", line 842, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://sheets.googleapis.com/v4/spreadsheets/1RaeZ4QpT3-ZCcIfBDKdtQJt0WDJKiLnBsB3dTC2PoGg/values/Sheet2%21A1%3AA10:append?valueInputOption=RAW&alt=json returned "Request had insufficient authentication scopes.">
Process finished with exit code 1
我固定了一个截图,证明我在 api 中拥有所有权限。 Google API 提前谢谢你。
【问题讨论】:
-
我认为从您的情况来看,您脚本中的范围可能不会反映到“token.json”中的刷新令牌中。那么这个流量呢? 1、删除“token.json”。 2. 运行脚本,再次授权。由此,创建了包括反映范围的刷新令牌的“token.json”。如果这不是您的解决方案,我很抱歉。
-
谢谢 Tanaike 成功了!
-
欢迎。我很高兴你的问题得到了解决。感谢您尝试并告诉我。
标签: python google-sheets google-sheets-api google-api-python-client