如果您有N 帐户并希望在每个帐户上上传视频,那么您必须运行以成功完成N OAuth 2 授权/身份验证流程。
对于这些N OAuth 流程中的每一个,在成功完成每个流程后,您必须将获得的凭据数据永久保存到计算机本地存储中的单独文件中。
这很可能被认为是您的应用程序的初始化步骤(尽管在以后的任何阶段,您都可以为您的应用程序需要注意的任何其他渠道重复它)。您的代码如下所示:
# run an OAuth flow; then obtain credentials data
# relative to the channel the app's user had chosen
# during that OAuth flow
from google_auth_oauthlib.flow import InstalledAppFlow
scopes = ['https://www.googleapis.com/auth/youtube']
flow = InstalledAppFlow.from_client_secrets_file(
client_secret_file, scopes)
cred = flow.run_console()
# build an YouTube service object such that to
# be able to retrieve the ID of the channel that
# the app's user had chosen during the OAuth flow
from googleapiclient.discovery import build
youtube = build('youtube', 'v3', credentials = cred)
response = youtube.channels().list(
part = 'id',
mine = True
).execute()
channel_id = response['items'][0]['id']
# save the credentials data to a JSON text file
cred_file = f"/path/to/credentials/data/dir/{channel_id}.json"
with open(cred_file, 'w', encoding = 'UTF-8') as json_file:
json_file.write(cred.to_json())
在上面,client_secret_file 是包含您从 Google Developers Console 获得的应用的客户端机密 JSON 文件的文件的完整路径。
随后,每次您要上传视频时,您都必须在应用程序中选择要将视频上传到哪个频道。从您的程序逻辑的角度来看,这意味着以下事情——假设您选择了 ID 为channel_id 的频道:请读入与channel_id 关联的凭据数据文件,以便将其内容传递给你的 YouTube 服务对象youtube 构造如下:
# read in the credentials data associated to
# the channel identified by its ID 'channel_id'
from google.oauth2.credentials import Credentials
cred_file = f"/path/to/credentials/data/dir/{channel_id}.json"
cred = Credentials.from_authorized_user_file(cred_file)
# the access token need be refreshed when
# the previously saved one expired already
from google.auth.transport.requests import Request
assert cred and cred.valid and cred.refresh_token
if cred.expired:
cred.refresh(Request())
# save credentials data upon it got refreshed
with open(cred_file, 'w', encoding = 'UTF-8') as json_file:
json_file.write(cred.to_json())
# construct an YouTube service object through
# which any API invocations are authorized on
# behalf of the channel with ID 'channel_id'
from googleapiclient.discovery import build
youtube = build('youtube', 'v3', credentials = cred)
运行此代码时,YouTube 服务对象 youtube 将被初始化,通过此对象发出的每个 API 端点调用都将代表 channel_id 标识的频道完成授权请求。
重要提示:您需要安装包Google Authentication Library for Python,google-auth,版本>= 1.21.3(google-auth v1.3.0 引入Credentials.from_authorized_user_file,v1.8.0 引入Credentials.to_json 和v1。 21.3 修复了后一个函数 wrt 其类'expiry 成员),以便将凭据对象 cred 保存到 JSON 文本文件并从中加载。
还有一个重要说明:上面的代码已尽可能简化。根本不处理错误条件。例如,当cred_file 在写出新的凭据数据文件时已经存在或cred_file 在读取应该已经存在的凭据数据时不存在时,上面的代码不会处理错误情况.