Google Sheets API调用报AttributeError: 'str' object has no attribute 'request'求助
问题原因排查
- 错误1:
discovery.build的credentials参数传入的是配置文件路径字符串,不符合参数要求
discovery.build方法的credentials参数要求传入经过实例化的谷歌认证凭据对象,不是凭据文件的路径字符串。你传入的字符串类型在后续调用API需要触发请求时,底层会尝试调用凭据对象的request方法,字符串没有该属性,直接触发你遇到的报错。
- 错误2:
spreadsheetId参数传入的是列表类型,不符合参数要求
该参数要求传入表格ID的字符串值,你用
[]包裹后变成了列表,即使认证问题解决后也会触发参数类型错误。
修正后的完整代码
import os from googleapiclient import discovery import pandas as pd # 新增导入服务账号认证工具类 from google.oauth2.service_account import Credentials credential_path = 'reference/config.json' scope = ['https://www.googleapis.com/auth/spreadsheets'] # 先从配置文件加载生成凭据对象 creds = Credentials.from_service_account_file(credential_path, scopes=scope) # 传入凭据对象初始化service service = discovery.build('sheets','v4',credentials=creds) # 这里替换成你实际的表格ID字符串,不要套列表 sheet_id = "替换为你的实际Google Sheets ID" ranges = 'Sheet1!D5:J36' sheet = service.spreadsheets() request = sheet.values().get(spreadsheetId=sheet_id, range=ranges, majorDimension='ROWS') response = request.execute() # 如需转成DataFrame可使用下行代码 # df = pd.DataFrame(response['values'])
内容的提问来源于stack exchange,提问作者bzflag
相关产品推荐
相关产品推荐

