如何在无浏览器环境下实现Youtube Data API v3的Python认证
无头Ubuntu服务器上完成Google OAuth2无浏览器认证方案
核心思路:先在有浏览器的本地机器上完成一次OAuth2认证,获取包含刷新令牌的持久化凭据文件,再将该文件部署到无头服务器,后续服务器可直接复用凭据(自动刷新访问令牌),无需再启动浏览器。
步骤1:本地生成带刷新令牌的持久化凭据
修改你的代码,添加凭据保存逻辑,确保获取到长期有效的刷新令牌(默认首次认证若不指定参数,可能不会返回刷新令牌):
import os import pickle from google.auth.transport.requests import Request import google_auth_oauthlib.flow import googleapiclient.discovery import googleapiclient.errors scopes = ["https://www.googleapis.com/auth/youtube.readonly"] TOKEN_FILE = "token.pickle" CLIENT_SECRETS_FILE = "client_secret.json" def main(): # 本地测试时临时禁用HTTPS验证,生产环境必须删除这行 os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" credentials = None # 检查是否已有保存的凭据 if os.path.exists(TOKEN_FILE): with open(TOKEN_FILE, 'rb') as token: credentials = pickle.load(token) # 无有效凭据时启动认证流程 if not credentials or not credentials.valid: if credentials and credentials.expired and credentials.refresh_token: # 凭据过期自动刷新 credentials.refresh(Request()) else: flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes) # 设置prompt='consent'强制获取刷新令牌 credentials = flow.run_local_server(port=8080, prompt='consent', open_browser=True) # 将凭据保存到本地文件 with open(TOKEN_FILE, 'wb') as token: pickle.dump(credentials, token) # 构建API客户端并调用接口 youtube = googleapiclient.discovery.build( "youtube", "v3", credentials=credentials) request = youtube.channels().list( part="snippet,contentDetails,statistics", mine=True ) response = request.execute() print(response) if __name__ == "__main__": main()
运行这段代码:
- 本地会自动打开浏览器,完成Google账号授权
- 认证成功后,当前目录会生成
token.pickle文件,里面包含访问令牌和长期有效的刷新令牌(除非你在Google账号中手动撤销授权)
步骤2:部署到无头Ubuntu服务器
- 将
client_secret.json和token.pickle两个文件上传到服务器的脚本目录 - 修改服务器上的代码,直接加载已保存的凭据,无需再启动认证流程:
import os import pickle from google.auth.transport.requests import Request import googleapiclient.discovery import googleapiclient.errors scopes = ["https://www.googleapis.com/auth/youtube.readonly"] TOKEN_FILE = "token.pickle" CLIENT_SECRETS_FILE = "client_secret.json" def main(): # 加载本地保存的凭据 credentials = None if os.path.exists(TOKEN_FILE): with open(TOKEN_FILE, 'rb') as token: credentials = pickle.load(token) # 凭据过期时自动刷新(全程无需浏览器) if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(Request()) # 保存刷新后的凭据 with open(TOKEN_FILE, 'wb') as token: pickle.dump(credentials, token) else: print("请先在本地生成token.pickle文件并上传到服务器") return # 构建API客户端并调用接口 youtube = googleapiclient.discovery.build( "youtube", "v3", credentials=credentials) request = youtube.channels().list( part="snippet,contentDetails,statistics", mine=True ) response = request.execute() print(response) if __name__ == "__main__": main()
运行服务器上的脚本,即可直接访问Google API,全程无需打开浏览器。
补充:解决本地认证时的重定向错误
你提到的点击链接出现重定向错误,是因为Google Cloud控制台未配置对应重定向URI:
- 登录Google Cloud控制台,进入你的项目
- 找到「API和服务」→「OAuth同意屏幕」→「已授权的重定向URI」
- 添加
http://localhost:8080(代码中run_local_server默认使用的端口),保存后即可解决该问题
内容的提问来源于stack exchange,提问作者jgore200377
相关产品推荐
相关产品推荐

