📜  Youtube 数据 API 订阅 |组 3

📅  最后修改于: 2021-10-19 06:10:49             🧑  作者: Mango

在之前的文章 Youtube Data API 订阅 | Set 1, Set 2 我们已经讨论过三种方法——

  • 检索与频道 ID 关联的订阅列表
  • 检索我的订阅,即与授权用户的帐户相关联
  • 检查订阅是否存在。

在本文中,我们将讨论以下两种方法 –

  • 插入订阅
  • 删除订阅

在继续之前,我们将首先讨论如何生成OAuth凭证。按照以下步骤生成客户端 ID 和密钥。

  1. 转到 Google Google Developers Console,然后单击页面右上角的登录。使用有效 Google 帐户的凭据登录。如果您没有 google 帐户,请先设置一个帐户,然后使用详细信息在 Google Developers 主页上登录。
  2. 现在导航到开发人员仪表板并创建一个新项目。
  3. 单击启用 API 选项
  4. 在搜索字段中,搜索Youtube Data API并选择下拉列表中的 Youtube Data API 选项。
  5. 您将被重定向到显示有关 Youtube Data API 信息的屏幕,以及两个选项: ENABLE 和 TRY API
  6. 单击启用选项以开始使用 API。
  7. 在 APIs & Services 下的侧边栏中,选择Credentials
  8. 在页面顶部,选择OAuth 同意屏幕选项卡。选择一个电子邮件地址,如果尚未设置,请输入产品名称,然后单击保存按钮。
  9. 凭据选项卡中,选择创建凭据下拉列表,然后选择OAuth 客户端 ID 。 OAuth 通常用于需要授权的情况,例如检索用户喜欢的视频。
  10. 选择其他应用程序类型,输入名称“YouTube Data API Myvideos”,然后单击“创建”按钮,然后单击“确定”。
  11. 单击客户端 ID 右侧的下载按钮以下载 JSON 文件。
  12. 将文件保存并重命名为client_secret.json并将其移动到工作目录。

使用 pip命令安装其他库:

注意:我们需要知道插入和删除订阅的频道 ID。请按照以下步骤查找频道 ID:

  1. 登录您的 YouTube 帐户。
  2. 浏览您要订阅的频道。
  3. 单击并打开频道。在 URL 中,您将在关键字channel/ 之后看到频道 ID

插入订阅的代码:此示例说明如何在由参数列表中提供的频道 ID 标识的 Youtube 频道中插入订阅。您可以通过更改snippet.resourceId.channelId属性来更改订阅。此示例添加对 Derek Banas 频道的订阅。

import os
import google.oauth2.credentials
import google_auth_oauthlib.flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google_auth_oauthlib.flow import InstalledAppFlow
  
# The CLIENT_SECRETS_FILE variable specifies
# the name of a file that contains
# client_id and client_secret.
CLIENT_SECRETS_FILE = "client_secret.json"
  
# This scope allows for full read/write access 
# to the authenticated user's account and 
# requires requests to use an SSL connection.
SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'
  
def get_authenticated_service():
  flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
  credentials = flow.run_console()
  return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)
  
def print_response(response):
  print(response)
  
# Build a resource based on a list of 
# properties given as key-value pairs.
# Leave properties with empty values out
# of the inserted resource.
def build_resource(properties):
  resource = {}
  for p in properties:
    # Given a key like "snippet.title", split into
    # "snippet" and "title", where "snippet" will be
    # an object and "title" will be a property in that object.
    prop_array = p.split('.')
    ref = resource
    for pa in range(0, len(prop_array)):
      is_array = False
      key = prop_array[pa]
  
      # For properties that have array values, convert a name like
      # "snippet.tags[]" to snippet.tags, and set a flag to handle
      # the value as an array.
      if key[-2:] == '[]':
        key = key[0:len(key)-2:]
        is_array = True
  
      if pa == (len(prop_array) - 1):
        # Leave properties without values 
        # out of inserted resource.
        if properties[p]:
          if is_array:
            ref[key] = properties[p].split(', ')
          else:
            ref[key] = properties[p]
      elif key not in ref:
        # For example, the property is "snippet.title", 
        # but the resource does not yet have a "snippet" 
        # object. Create the snippet object here. 
        # Setting "ref = ref[key]" means that in the
        # next time through the "for pa in range ..." loop,
        # we will be setting a property in the
        # resource's "snippet" object.
        ref[key] = {}
        ref = ref[key]
      else:
        # For example, the property is "snippet.description",
        #  and the resource already has a "snippet" object.
        ref = ref[key]
  return resource
  
# Remove keyword arguments that are not set
def remove_empty_kwargs(**kwargs):
  good_kwargs = {}
  if kwargs is not None:
    for key, value in kwargs.items():
      if value:
        good_kwargs[key] = value
  return good_kwargs
  
def subscriptions_insert(client, properties, **kwargs):
  resource = build_resource(properties)
  kwargs = remove_empty_kwargs(**kwargs)
  
  response = client.subscriptions().insert(
    body = resource,**kwargs).execute()
  
  return print_response(response)
  
  
if __name__ == '__main__':
  # When running locally, disable OAuthlib's 
  # HTTPs verification. When running in production
  # * do not * leave this option enabled.
  os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
  client = get_authenticated_service()
    
  subscriptions_insert(client, 
    {'snippet.resourceId.kind': 'youtube# channel',
     'snippet.resourceId.channelId': 'UCwRXb5dUK4cvsHbx-rGzSgw'},
    part ='snippet')

输出:
在执行代码时,您将被要求提供授权代码。要获取代码,您需要按照以下行上方的命令提示符屏幕中提到的链接进行操作:输入授权代码。

现在点击链接并复制粘贴您将通过授予权限获得的授权代码。

如果您看到,从上面的输出中可以清楚地看出我已成功订阅该频道。

删除订阅的代码:此示例说明如何删除订阅。 id参数是订阅 ID,即您可以在插入订阅时从命令提示符记下,或者您可以运行代码以列出所有订阅并记下所需订阅的订阅 ID。在这个例子中,我删除了我在上面讨论的代码中添加的订阅。

import os
import google.oauth2.credentials
import google_auth_oauthlib.flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google_auth_oauthlib.flow import InstalledAppFlow
  
# The CLIENT_SECRETS_FILE variable specifies
#  the name of a file that contains client_id 
# and client_secret.
CLIENT_SECRETS_FILE = "client_secret.json"
  
# This scope allows for full read/write access 
# to the authenticated user's account and
# requires requests to use an SSL connection.
SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'
  
def get_authenticated_service():
  flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
  credentials = flow.run_console()
  return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)
  
def print_response(response):
  print(response)
  
# Build a resource based on a list of properties 
# given as key-value pairs. Leave properties with
# empty values out of the inserted resource.
def build_resource(properties):
  resource = {}
  for p in properties:
    # Given a key like "snippet.title", split into
    # "snippet" and "title", where "snippet" will be
    # an object and "title" will be a property in that object.
    prop_array = p.split('.')
    ref = resource
    for pa in range(0, len(prop_array)):
      is_array = False
      key = prop_array[pa]
  
      # For properties that have array values, convert a name like
      # "snippet.tags[]" to snippet.tags, and set a flag to handle
      # the value as an array.
      if key[-2:] == '[]':
        key = key[0:len(key)-2:]
        is_array = True
  
      if pa == (len(prop_array) - 1):
        # Leave properties without values out of inserted resource.
        if properties[p]:
          if is_array:
            ref[key] = properties[p].split(', ')
          else:
            ref[key] = properties[p]
      elif key not in ref:
        # For example, the property is "snippet.title", 
        # but the resource does not yet have a "snippet" 
        # object. Create the snippet object here. 
        # Setting "ref = ref[key]" means that in the
        # next time through the "for pa in range ..." loop, 
        # we will be setting a property in the
        # resource's "snippet" object.
        ref[key] = {}
        ref = ref[key]
      else:
        # For example, the property is "snippet.description", 
        # and the resource already has a "snippet" object.
        ref = ref[key]
  return resource
  
# Remove keyword arguments that are not set
def remove_empty_kwargs(**kwargs):
  good_kwargs = {}
  if kwargs is not None:
    for key, value in kwargs.items():
      if value:
        good_kwargs[key] = value
  return good_kwargs
  
def subscriptions_delete(client, **kwargs):
  kwargs = remove_empty_kwargs(**kwargs)
  response = client.subscriptions().delete(**kwargs).execute()
  
  return print_response(response)
  
if __name__ == '__main__':
  # When running locally, disable OAuthlib's HTTPs
  #  verification. When running in production 
  # * do not * leave this option enabled.
  os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
  client = get_authenticated_service()
    
  subscriptions_delete(client,
    id ='AP1TRjqBsvvxCyjQuHtwgyzj5rqdRr1YQFrBIp0pPvU')

输出:
在执行代码时,您将被要求提供授权代码。要获取代码,您需要按照以下行上方的命令提示符屏幕中提到的链接进行操作:输入授权代码。

现在点击链接并复制粘贴您将通过授予权限获得的授权代码。

您可以从上面的输出中看到,频道再次显示订阅选项。

参考:

  1. https://developers.google.com/youtube/v3/docs/subscriptions
  2. https://developers.google.com/youtube/v3/docs/