【问题标题】:AttributeError: 'str' object has no attribute 'request'AttributeError:“str”对象没有属性“request”
【发布时间】:2021-10-29 09:40:08
【问题描述】:

我能够成功建立连接而没有任何错误,但是当我尝试从工作表中读取数据时,我遇到了 AttributeError

import os
from googleapiclient import discovery
import pandas as pd

credential = 'reference/config.json'
api_name = 'sheets'
api_version = 'v4'
scope = ['https://www.googleapis.com/auth/spreadsheets']

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

sheet_id = [sheet_id]
ranges = 'Sheet1!D5:J36'

sheet = service.spreadsheets()
request = sheet.values().get(spreadsheetId=sheet_id, range=ranges, majorDimension='ROWS')
response = request.execute()

AttributeError: 'str' object has no attribute 'request' 发生在倒数第二行 (request = sheet.values().get(spreadsheetId=sheet_id, range=ranges, majorDimension='行')

我按照文档页面https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get提供的确切说明进行操作

【问题讨论】:

    标签: python-3.x google-sheets google-api-client google-api-python-client


    【解决方案1】:

    以前我没有使用授权来让我的凭据工作,在下面的代码中,我添加了授权片段,然后是让代码正常工作的凭据

    from __future__ import print_function
    import os.path
    from googleapiclient.discovery import build
    from google.oauth2 import service_account
    
    SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
    SERVICE_ACCOUNT_FILE = 'config.json'
    #config.json is your GCP Service Account Credential file which gets downloaded
    
    creds = None
    creds = service_account.Credentials.from_service_account_file(
            SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    
    # The ID and range of a sample spreadsheet.
    SAMPLE_SPREADSHEET_ID = '[SpreadsheetID]'
    SAMPLE_RANGE_NAME = '[SheetName]![Range]'
    
    service = build('sheets', 'v4', credentials=creds)
    
    # Call the Sheets API
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                                    range=SAMPLE_RANGE_NAME).execute()
    #values = result.get('values', [])
    print(result)
    

    【讨论】:

      猜你喜欢
      • 2022-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-10
      • 2021-10-04
      • 2019-12-02
      • 2021-09-25
      • 2014-03-04
      相关资源
      最近更新 更多