Python使用gspread调用Google Sheets API报429配额超限如何处理
问题原因
你触发429错误的核心原因是while result.cell(i, 1).value != "" 这个循环中,每执行一次result.cell()就会向Google Sheets API发起1次读请求,如果表格行数较多,短时间内请求数就会超过「单用户每分钟读请求」的配额限制。
修改方案
方法1:直接添加延迟(适配现有代码,操作最简单)
首先在代码顶部导入time模块,然后在while循环内部加time.sleep()控制请求频率,延迟秒数可根据表格行数调整,一般0.1~1秒即可避免超限:
from googleapiclient.discovery import build from google.oauth2 import service_account from oauth2client.service_account import ServiceAccountCredentials import gspread import time # 新增导入time模块 scope = ['https://www.googleapis.com/auth/spreadsheets', "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"] creds = ServiceAccountCredentials.from_json_keyfile_name(r'C:\Users\Camila\Python-projects\avon-chave-sheets.json', scope) client = gspread.authorize(creds) result = client.open("Dados_faturados_dia_avon").worksheet("dadosfaturados") i = 1 while result.cell(i, 1).value != "": i = i + 1 time.sleep(0.2) # 每次循环后等待0.2秒,可根据实际运行情况调整数值 result.update_cell(i,1, valores)
方法2:优化请求逻辑(更推荐,从根源减少请求量)
不用逐行读取判断,直接一次性拉取第一列的所有数据,仅需要发起1次API请求,完全避免短时间大量读请求的问题:
from googleapiclient.discovery import build from google.oauth2 import service_account from oauth2client.service_account import ServiceAccountCredentials import gspread scope = ['https://www.googleapis.com/auth/spreadsheets', "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"] creds = ServiceAccountCredentials.from_json_keyfile_name(r'C:\Users\Camila\Python-projects\avon-chave-sheets.json', scope) client = gspread.authorize(creds) result = client.open("Dados_faturados_dia_avon").worksheet("dadosfaturados") # 一次性读取第一列所有值,仅发起1次API请求 col1_values = result.col_values(1) # 统计非空行数量 i = len(col1_values) + 1 result.update_cell(i,1, valores)
补充说明
- 若你的业务场景需要高频调用API,可适当调大
time.sleep()的数值,数值越大请求频率越低,越不容易触发配额限制 - 方法2的执行效率远高于逐行读取,即使后续表格行数持续增长也不会轻易出现配额超限问题
内容的提问来源于stack exchange,提问作者Camila leaoavon
相关产品推荐
相关产品推荐

