【问题标题】:Authenticating to use Google Sheets REST api with Python通过 Python 进行身份验证以使用 Google Sheets REST api
【发布时间】:2017-07-24 16:26:55
【问题描述】:

我正在尝试使用本地 (mac) python 程序将一行附加到谷歌工作表。我天真地认为下面的 sn-p 就足够了:

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)

我收到错误:

401:“请求缺少所需的身份验证凭据。 预期的 OAuth 2 访问令牌、登录 cookie 或其他有效的 身份验证凭据。

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

谁能提供一个例子来说明如何去做。

【问题讨论】:

    标签: python-2.7 oauth-2.0 google-spreadsheet-api


    【解决方案1】:

    您可以尝试documentation中的示例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)
    

    还有

    由于您正在使用从其他用户访问数据的应用程序,请打开本指南以获取 Authorize Requests 以了解有关身份验证凭据的更多信息。

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 2016-04-16
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      • 2015-04-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-04
      相关资源
      最近更新 更多