使用Python的YouTube API批量传视频遇配额超限,求解决方案
YouTube API批量上传配额超限问题解决方案
问题根源分析
每次视频上传(videos.insert)消耗1600单位配额,你额外调用的videos.update又消耗50单位,单次上传总计1650单位。YouTube API每日配额为10000单位,批量上传数量较多时会快速耗尽配额;若当日已有其他API调用消耗配额,也会导致后续上传失败。
核心优化方案:减少API请求次数
直接在上传时设置发布时间和隐私状态,无需额外调用videos.update,单次上传配额消耗从1650降至1600,同时减少网络请求次数。
修改后的关键代码片段:
# 创建视频对象时直接配置发布时间和隐私状态 video = { 'snippet': { 'title': f'{title} - # {titleNum}', 'description': '', 'categoryId': '22', 'tags': ['tag1', 'tag2', 'tag3'], 'defaultLanguage': 'en' }, 'status': { 'privacyStatus': 'private', 'selfDeclaredMadeForKids': False, 'publishAt': scheduled_time.strftime('%Y-%m-%dT%H:%M:%SZ') # 直接指定发布时间 } } # 上传视频,无需后续update请求 try: response = youtube.videos().insert( part='snippet,status', body=video, media_body=MediaFileUpload(video_path) ).execute() video_id = response['id'] print(f'The video was uploaded with ID: {video_id}') print(f'Video "{video_file}" scheduled for {scheduled_time.strftime("%Y-%m-%d %H:%M:%S")} IST') except HttpError as error: print(f'An HTTP error {error.resp.status} occurred: {error.content}')
其他解决方案
- 配额耗尽后的重试逻辑:捕获
403 QuotaExceeded错误,等待配额重置(每日太平洋时间午夜重置)后继续上传:except HttpError as error: if error.resp.status == 403 and 'quotaExceeded' in str(error.content): print("配额已耗尽,等待24小时后重试...") time.sleep(86400) # 等待一天后重新执行当前视频上传 else: print(f'An HTTP error {error.resp.status} occurred: {error.content}') - 多账号轮换:准备多个YouTube账号的OAuth凭证,当一个账号配额耗尽时,自动切换到下一个账号继续上传。
- 申请提高配额:如果是正规商业用途,可通过Google Cloud控制台提交配额提升申请,说明具体使用场景和需求。
额外代码修正
你的凭证保存部分存在重复写入的冗余代码,可简化为:
# 保存凭证供下次使用 with open('token.json', 'w') as token_file: token_file.write(creds.to_json())
内容的提问来源于stack exchange,提问作者Vaishnav Dounde
相关产品推荐
相关产品推荐

