通过Python验证使用Google表格REST api

use*_*244 0 oauth-2.0 python-2.7 google-spreadsheet-api

我正在尝试使用本地(mac)python程序向google工作表附加一行.我天真地认为下面的代码就足够了:

import requests
url = "https://sheets.googleapis.com/v4/spreadsheets/SHEETID/values/Expenses!A1:D1:append?valueInputOption=USER_ENTERED"
data = {
    "range": "Expenses!A1:D1",
    "majorDimension": "ROWS",
    "values": [
        [NEW ROW DATA]]
    ],
}


resp = requests.post(url, data)
Run Code Online (Sandbox Code Playgroud)

我收到错误:

401:"请求缺少必需的身份验证凭据.预期的OAuth 2访问令牌,登录cookie或其他有效的身份验证凭据.

我不确定如何为google sheet rest api设置身份验证.

任何人都可以举例说明如何解决这个问题.

Mαπ*_*π.0 5

您可以在文档中尝试示例python代码.

"""
BEFORE RUNNING:
---------------
1. If not already done, enable the Google Sheets API
   and check the quota for your project at
   https://console.developers.google.com/apis/api/sheets
2. Install the Python client library for Google APIs by running
   `pip install --upgrade google-api-python-client`
"""
from pprint import pprint

from googleapiclient import discovery

# TODO: Change placeholder below to generate authentication credentials. See
# https://developers.google.com/sheets/quickstart/python#step_3_set_up_the_sample
#
# Authorize using one of the following scopes:
#     'https://www.googleapis.com/auth/drive'
#     'https://www.googleapis.com/auth/drive.file'
#     'https://www.googleapis.com/auth/spreadsheets'
credentials = None

service = discovery.build('sheets', 'v4', credentials=credentials)

# The ID of the spreadsheet to update.
spreadsheet_id = 'my-spreadsheet-id'  # TODO: Update placeholder value.

# The A1 notation of a range to search for a logical table of data.
# Values will be appended after the last row of the table.
range_ = 'my-range'  # TODO: Update placeholder value.

# How the input data should be interpreted.
value_input_option = ''  # TODO: Update placeholder value.

# How the input data should be inserted.
insert_data_option = ''  # TODO: Update placeholder value.

value_range_body = {
    # TODO: Add desired entries to the request body.
}

request = service.spreadsheets().values().append(spreadsheetId=spreadsheet_id, range=range_, valueInputOption=value_input_option, insertDataOption=insert_data_option, body=value_range_body)
response = request.execute()

# TODO: Change code below to process the `response` dict:
pprint(response)
Run Code Online (Sandbox Code Playgroud)

并且

由于您正在使用从其他用户访问数据的应用程序,因此打开本授权请求指南以了解有关身份验证凭据的更多信息.