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

使用YouTube Data API时避免手动输入authorization code的方案咨询

解决YouTube API服务器部署时OAuth2无手动授权的问题

要解决服务器上无法手动输入授权码的问题,核心是提前在本地完成一次OAuth2授权,保存包含刷新令牌(refresh_token)的凭据文件,服务器端直接加载该文件自动获取/刷新访问令牌,具体步骤和修改后的代码如下:

步骤1:修改本地代码,保存授权凭据

在本地运行时,将授权后的凭据保存到文件(比如token.json),这样后续服务器无需再手动授权。修改原代码的凭据获取部分:

# -*- coding: utf-8 -*-

import os
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
from googleapiclient.http import MediaFileUpload
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request

scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]

def main():
    # 本地运行时启用(服务器部署时注释/删除)
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = "client_secret_07607-7kkbsf6.apps.googleusercontent.com.json"
    token_file = "token.json"

    credentials = None
    # 检查是否已保存凭据文件
    if os.path.exists(token_file):
        credentials = Credentials.from_authorized_user_file(token_file, scopes)
    
    # 如果没有有效凭据,重新授权
    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)
            credentials = flow.run_console()
        
        # 保存凭据到文件
        with open(token_file, "w") as token:
            token.write(credentials.to_json())

    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

    # 原有的直播创建请求代码不变
    request = youtube.liveBroadcasts().insert(
        part="snippet,contentDetails,status",
        body={
          "contentDetails": {
            "enableClosedCaptions": True,
            "enableContentEncryption": True,
            "enableDvr": True,
            "enableEmbed": True,
            "recordFromStart": True,
            "startWithSlate": True
          },
          "snippet": {
            "title": "Didou Test broadcast",
            "scheduledStartTime": "2022-08-17T16:48:09Z",
            "description": "my video description"
          },
          "status": {
            "privacyStatus": "public"
          }
        }
    )
    response = request.execute()
    print(response)

if __name__ == "__main__":
    main()

步骤2:本地运行生成token.json

在本地环境运行上述代码,按照提示访问授权URL,输入授权码完成验证。运行后会在当前目录生成token.json文件,这个文件包含了refresh_token,可以用来自动刷新过期的access_token。

步骤3:服务器部署配置

  1. 将client_secret_xxx.json和token.json上传到服务器的代码目录中。
  2. 注释或删除服务器代码中的os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"这一行(生产环境必须禁用不安全传输)。
  3. 确保服务器环境安装了所有依赖包:google-auth-oauthlib、google-api-python-client。

关键说明

  • access_type=offline:原代码中run_console()默认会请求offline类型的授权,因此会返回refresh_token,允许后续无需手动交互即可刷新令牌。
  • 凭据自动刷新:代码中会检查凭据是否过期,如果过期且存在refresh_token,会自动调用credentials.refresh(Request())获取新的access_token。
  • 安全注意:client_secret_xxx.json和token.json包含敏感信息,不要提交到公共代码仓库,服务器上要限制文件访问权限。

内容的提问来源于stack exchange,提问作者adilou1981

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 00:21:40