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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:15:07