Python更新Google Sheet触发gspread 429配额超限错误如何解决
429配额超限报错解决方案
错误原因
你触发的429错误是Google Sheets API默认速率限制导致的:默认单用户每分钟写入请求配额为60次,你在循环中逐次调用update_cell()方法,每次调用都会发起一次独立的API请求,短时间内请求量超过阈值就会触发资源耗尽报错。
优化方案
- 优先使用批量写入:不要循环调用单次单元格更新接口,先把所有要更新的单元格数据整理成指定格式,再通过批量接口一次性提交,不管更新多少单元格仅需1次API请求,优化示例如下:
scope = ### creds = Credentials.from_service_account_file("v1Timetable.json", scopes=scope) client = gspread.authorize(creds) google_sh = client.open("v1Timetable") sheet1 = google_sh.get_worksheet(1) # 初始化更新队列 update_queue = [] for k in range(0, numberOfGroups): for l in c.GetGroups(): if l == instance.GetStudentsGroupById(str(k + 1)): # info is updated here if grNumber == 0: update_queue.append({"range": f"R{d+1}C{t+1}", "values": [[str(info)]]}) if grNumber == 1: update_queue.append({"range": f"R{d+8}C{t+1}", "values": [[str(info)]]}) if grNumber == 2: update_queue.append({"range": f"R{d+15}C{t+1}", "values": [[str(info)]]}) if grNumber == 3: update_queue.append({"range": f"R{d+22}C{t+1}", "values": [[str(info)]]}) # 一次性提交所有更新请求 sheet1.batch_update({ "data": update_queue, "valueInputOption": "RAW" })
- 补充请求间隔(仅适合极小写入量场景):如果你的更新需求很少、不想调整批量逻辑,可以在每次
update_cell()调用后增加1秒延时,控制每分钟请求数不超过60,示例如下:
import time # 每次写入后加延时 sheet1.update_cell(d + 1, t + 1, str(info)) time.sleep(1)
- 申请提升配额:如果批量写入后仍满足不了你的业务写入量需求,可以前往Google Cloud控制台对应项目的Sheets API配额管理页面,提交配额提升申请,审核通过后即可获得更高的写入速率上限。
内容的提问来源于stack exchange,提问作者JJ Lim
相关产品推荐
相关产品推荐

