如果你有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())
Above, 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
.
重要提示:您需要安装该软件包适用于 Python 的 Google 身份验证库 https://github.com/GoogleCloudPlatform/google-auth-library-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 修复了后一个函数。它的阶级'expiry
成员),用于凭证对象cred
保存到 JSON 文本文件并从中加载。
还有一个重要的注意事项:上面的代码已尽可能简化。错误情况根本不被处理。例如,上面的代码不处理以下错误情况:cred_file
在写出新的凭证数据文件时或在cred_file
在读取应该已经存在的凭据数据时不存在。