Python调用YouTube API上传视频失败,遇DefaultCredentialsError求助
问题解决:YouTube API视频上传凭证错误及代码修正
核心问题分析
你的报错是凭证认证方式错误:google.auth.default()适用于Google Cloud服务账号认证,但YouTube视频上传需要使用OAuth2用户授权凭证,而非服务账号。同时代码中还存在几处参数错误,导致无法正常执行。
修正步骤及代码
1. 安装依赖
确保安装OAuth2相关依赖库:
pip install google-auth-oauthlib google-auth-httplib2
2. 修正后的完整代码
import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.http import MediaFileUpload import os def upload_video_to_youtube(video_file, title, description, tags): try: # 配置OAuth2认证 client_secrets_file = "client_secret.json" scopes = ["https://www.googleapis.com/auth/youtube.upload"] # 检查本地保存的凭证,避免重复授权 credentials_path = "token.json" if os.path.exists(credentials_path): credentials, _ = google.auth.load_credentials_from_file(credentials_path, scopes=scopes) else: # 启动本地浏览器授权流程 flow = InstalledAppFlow.from_client_secrets_file(client_secrets_file, scopes) credentials = flow.run_local_server(port=0) # 保存凭证到本地文件 with open(credentials_path, "w") as token: token.write(credentials.to_json()) # 修正build函数参数:第一个参数为API名称"youtube" youtube = build("youtube", "v3", credentials=credentials) # 定义视频元数据 request_body = { "snippet": { "title": title, "description": description, "tags": tags, "categoryId": "22" # API要求为字符串类型 }, "status": { "privacyStatus": "private" } } # 初始化可恢复上传对象 media = MediaFileUpload(video_file, chunksize=1024*1024, resumable=True) request = youtube.videos().insert( part="snippet,status", body=request_body, media_body=media ) # 执行可恢复上传循环,处理进度 response = None while response is None: status, response = request.next_chunk() if status: print(f"上传进度: {int(status.progress() * 100)}%") print(f"视频上传成功,ID: {response['id']}") except HttpError as error: print(f"上传时发生HTTP错误: {error}") except Exception as e: print(f"其他错误: {e}") # 调用函数时,tags需传入列表类型而非字符串 upload_video_to_youtube("video.mp4", "test", "test description", ["test"])
关键修改点说明
- 认证方式替换:改用
InstalledAppFlow处理OAuth2用户授权,首次运行会自动打开浏览器引导你登录Google账号完成授权,凭证会保存在本地token.json中,后续运行无需重复授权。 - build函数参数修正:原代码中
build(client_secrets_file,"youtube", "v3", credentials=credentials)参数顺序错误,正确顺序为build(api_name, api_version, credentials=...)。 - tags参数类型修正:YouTube API要求
tags为列表类型,原调用时传入的字符串"test"改为列表["test"]。 - 可恢复上传处理:原代码直接调用
execute()不适用于大文件上传,改用next_chunk()循环处理上传进度,支持断点续传。 - categoryId类型修正:API要求
categoryId为字符串,原代码中的整数22改为字符串"22"。
额外注意事项
- 确保
client_secret.json文件放在脚本同一目录下,该文件需从Google Cloud控制台的OAuth2客户端ID页面下载。 - 用于授权的Google账号必须关联有效的YouTube频道,且已在Google Cloud控制台启用YouTube Data API v3。
内容的提问来源于stack exchange,提问作者Test000
相关产品推荐
相关产品推荐

