使用Python的多个帐户的YouTube数据API

使用Python的多个帐户的YouTube数据API

问题描述:

我正在开发一个应用程序,可以帮助我的一个朋友更好地组织他的YouTube频道.他在不同的Google帐户中拥有多个渠道.我正在使用Python进行开发,由于我似乎是唯一的选择,因此我目前对计划使用的YouTube数据API并没有太多的经验.

I am developing an application that is supposed to help a friend of mine better organize his YouTube channels. He has multiple channels on different Google accounts. I'm developing this in Python and I currently don't have too much experience with the YouTube Data API, which I'm planning on using, since it seems like the only option.

应用程序本身不是很复杂.它唯一需要做的就是上传具有指定标题,说明和其他属性的视频,并且还应该可以在视频上写评论.我在Google Developers Console中启动了一个简单的应用程序,启用了YouTube数据API,并创建了API密钥和OAUTH-Client ID.

The application itself isn't very complicated. The only things it needs to be able to do is upload videos, with a specified title, description and other properties and it should also be possible to write comments on videos. I started a simple application in the Google Developers Console, enabled the YouTube Data API and created an API key and an OAUTH-Client ID.

到目前为止,我已经设法在视频上发表评论,但是似乎每次我运行Python脚本(当前它只是一个发布单个评论的简单脚本)时,Google都希望我明确选择我要使用的帐户使用,并且每次运行脚本时都必须授予该脚本的权限.

So far I've managed to post comments on videos, but it seems like every time I run the Python script (currently its just a simple script that posts a single comment) Google wants me to explicitly choose which account I want to use and I have to give permission to the script every time I run it.

有没有一种方法可以只运行一次脚本并告诉Google我要使用哪个帐户来发表评论,提供所有权限,然后Google记住这一点,所以我不必每次都明确地授予权限?

Is there a way I can just run the script once and tell Google which account I want to use to post the comment, give all the permissions and Google then remembers that so I don't have to explicitly give permissions every time?

然后,我将如何切换帐户并使用该帐户进行上传,因为当前,当Google客户端弹出时,在运行脚本时,我总是需要选择一个帐户.

Also how would I be able to then switch accounts and make uploads with that one, because currently I always need to choose one, when the Google client pops up, when running the script.

我听说您可以获得Google授权的应用程序,这会有所帮助吗?或者如果我只是将我的应用程序保持在测试状态而不是正式投入生产就可以了吗?

I've heard you can get an application authorized by Google, would that help with this or is it fine if I just keep my app in test and not in production?

如果您有 N 个帐户,并且要在每个帐户上上传视频,则必须运行以成功完成 N OAuth 2授权/身份验证流程.

If you have N accounts and want to upload videos on each of them, then you'll have to run to successful completion N OAuth 2 authorization/authentication flows.

对于每个 N 个OAuth流程,成功完成每个OAuth流程后,您都必须将获取的凭据数据永久保存到计算机本地存储中的单独文件中.

For each of these N OAuth flows, upon completing each one successfully, you'll have to make persistent the obtained credentials data to a separate file within your computer local storage.

这很可能被认为是应用程序的初始化步骤(尽管在以后的任何阶段,您都可以针对需要您的应用程序注意的任何其他渠道重复执行此步骤).您的代码如下所示:

This could well be conceived as an initialization step of your app (although, at any later stage, you may well repeat it for any additional channel that you need your app be aware of). Your code would look like:

# 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文件的文件的完整路径.

Above, client_secret_file is the full path to the file containing your app's client secret JSON file that you've obtained from Google Developers Console.

随后,每次您要上传视频时,都必须从应用程序中选择要将视频上传到哪个频道.从程序逻辑的角度来看,这意味着以下事情-假设您选择了ID为 channel_id 的通道:请确实读取与 channel_id相关联的凭据数据文件用于将其内容传递到如下所示的YouTube服务对象 youtube :

Subsequently, each time you'll want to upload a video, you'll have to choose from within the app to which channel to upload that video. From the perspective of the logic of your program that would imply the following thing -- say you've chosen the channel of which ID is channel_id: do read in the credentials data file associated to channel_id for to pass its content to your YouTube service object youtube constructed as shown below:

# 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 .

Upon running this code, the YouTube service object youtube will be initialized such a way that each an every API endpoint call that is issued through this object will accomplish an authorized request on behalf of the channel identified by channel_id.

重要说明:您需要已安装软件包适用于Python的Google身份验证库 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文本文件加载.

An important note: you need to have installed the package Google Authentication Library for Python, google-auth, version >= 1.21.3 (google-auth v1.3.0 introduced Credentials.from_authorized_user_file, v1.8.0 introduced Credentials.to_json and v1.21.3 fixed this latter function w.r.t. its class' expiry member), for the credentials object cred to be saved to and loaded from JSON text files.

还有一个重要说明:上面的代码已尽可能简化.错误条件根本不处理.例如,当在写出新凭证数据文件时 cred_file 已经存在或当当时 cred_file 不存在时,上面的代码无法处理错误情况.读取应该已经存在的凭据数据.

Also an important note: the code above is simplified as much as possible. Error conditions are not handled at all. For example, the code above does not handle the error situation when cred_file already exists at the time of writing out a new credentials data file or when cred_file does not exist at the time of reading in credentials data that's supposed to already exist.