You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Google Sheet API时遇AttributeError: 'str'对象无'valid'属性

解决Google Sheets API中的AttributeError: 'str' object has no attribute 'valid'错误

作为刚接触Google Sheets API的新手,你遇到的这个错误其实是个很典型的变量初始化问题,咱们来拆解一下:

错误根源

你一开始把creds变量赋值成了字符串类型的凭证文件路径:

creds = 'C:\\Users\\Nimit\\Desktop\\Google\\credentials.json'

但后续代码里需要用creds.valid来判断凭证是否有效——字符串对象根本没有valid这个属性,自然就触发了AttributeError。

修正方案

把creds的初始值改成None,让后续的凭证加载逻辑正常运行:

修改后的完整代码:

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']

# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1dQ_WGhmQHClQ8tY-0djLhOltF9aRhtU7p2WmDEdRFYg'
SAMPLE_RANGE_NAME = 'Sheet1!A2:E2'

def main():
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    # 初始值设为None,而不是字符串路径
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'C:\\Users\\Nimit\\Desktop\\Google\\credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    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', [])

    if not values:
        print('No data found.')
    else:
        print('Name, Major:')
        for row in values:
            # Print columns A and E, which correspond to indices 0 and 4.
            print('%s, %s' % (row[0], row[4]))

if __name__ == '__main__':
    main()

关键修改点说明

  1. 把creds初始化为None,这样当没有token.pickle文件时,if not creds的判断会成立,进入授权流程。
  2. 在InstalledAppFlow.from_client_secrets_file里传入正确的凭证文件路径,而不是把路径赋值给creds。

这样修改后,creds要么是None,要么是加载后的凭证对象(带有valid、expired等属性),就能正常执行后续的凭证校验和API调用了。

内容的提问来源于stack exchange,提问作者Nimit Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:18:47