ارسال اولین درخواست

توجه: YouTube Content ID API برای استفاده شرکای محتوای YouTube در نظر گرفته شده است و برای همه توسعه دهندگان یا همه کاربران YouTube قابل دسترسی نیست. اگر API شناسه محتوای YouTube را به‌عنوان یکی از سرویس‌های فهرست شده در Google API Console نمی‌بینید، برای کسب اطلاعات بیشتر درباره YouTube Partner Program به مرکز راهنمایی YouTube مراجعه کنید.

این آموزش گام به گام نحوه ساخت یک اسکریپت را توضیح می دهد که به ContentOwnersService متصل می شو�� و اطلاعات مربوط به مالک محتوای معین را بازیابی می کند. نمونه کد کامل در انتهای آموزش ارائه شده است. در حالی که این کد در پایتون نوشته شده است، کتابخانه های سرویس گیرنده برای سایر زبان های برنامه نویسی محبوب نیز در دسترس هستند.

الزامات

ساخت یک اسکریپت برای ارسال درخواست های API

مراحل زیر نحوه ساخت یک اسکریپت برای ارسال درخواست API Content ID YouTube را توضیح می دهد.

مرحله 1: اسکریپت اصلی را ایجاد کنید

اسکریپت زیر پارامترهای خط فرمان زیر را می پذیرد و مقادیر را روی متغیر جهانی FLAGS تنظیم می کند:

  • پارامتر content_owner_id لازم است و مالک محتوای CMS را که در حال بازیابی اطلاعات در مورد آن هستید، شناسایی می کند.
  • پارامتر logging_level سطح جزئیات ورود به سیستم را برای اسکریپت مشخص می کند.
  • پارامتر help باعث می شود که اسکریپت لیستی از پارامترهایی را که درک می کند به بیرون ارائه دهد.
#!/usr/bin/python2.6
# -*- coding: utf-8 -*-

import gflags
import logging
import sys
import os

from datetime import *

# Define flags. The gflags module makes it easy to define command-line params
# for an application. Run this program with the '--help' argument to see all
# of the flags that it understands.
FLAGS = gflags.FLAGS
gflags.DEFINE_string('content_owner_id', None, ('Required flag. '
     'Identifies the content owner whose details are printed out.'))
gflags.MarkFlagAsRequired('content_owner_id')
gflags.DEFINE_enum('logging_level', 'ERROR',
    ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
    'Set the level of logging detail.')


def main(argv):
  # Let the gflags module process the command-line arguments
  try:
    argv = FLAGS(argv)
  except gflags.FlagsError, e:
    print '%s\nUsage: %s ARGS\n%s' % (e, argv[0], FLAGS)
    sys.exit(1)

  # Set the logging according to the command-line flag
  logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))

if __name__ == '__main__':
  main(sys.argv)

مرحله 2: احراز هویت و مجوز کاربر را فعال کنید

در این مرحله، مجوز OAuth 2.0 را در اسکریپت قرار می دهیم. این به کاربر در حال اجرا اسکریپت را قادر می‌سازد تا به اسکریپت اجازه دهد تا درخواست‌های API منتسب به حساب کاربر را انجام دهد.

مرحله 2a: یک فایل client_secrets.json ایجاد کنید

API شناسه محتوای YouTube برای احراز هویت به فایل client_secrets.json نیاز دارد که حاوی اطلاعاتی از کنسول API است. همچنین باید درخواست خود را ثبت کنید . برای توضیح کامل تر در مورد نحوه عملکرد احراز هویت ، راهنمای احراز هویت را ببینید.

 {
  "web": {
    "client_id": "INSERT CLIENT ID HERE",
    "client_secret": "INSERT CLIENT SECRET HERE",
    "redirect_uris": [],
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token"
  }
}

مرحله 2b: کد احراز هویت را به اسکریپت خود اضافه کنید

برای فعال کردن احراز هویت و مجوز کاربر، باید عبارات import زیر را اضافه کنید:

from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run

در مرحله بعد، یک شی FLOW با استفاده از رمزهای سرویس گیرنده پیکربندی شده در مرحله 2a ایجاد می کنیم. اگر کاربر به برنامه ما اجازه دهد درخواست‌های API را از طرف کاربر ارسال کند، اعتبارنامه‌های حاصل در یک شی Storage برای استفاده بعدی ذخیره می‌شوند. اگر اعتبارنامه منقضی شود، کاربر باید مجدداً مجوز برنامه ما را صادر کند.

کد زیر را به انتهای تابع main اضافه کنید:

  # Set up a Flow object to be used if we need to authenticate.
  FLOW = flow_from_clientsecrets('client_secrets.json',
      scope='https://www.googleapis.com/auth/youtubepartner',
      message='error message')

  # The Storage object stores the credentials. If it doesn't exist, or if
  # the credentials are invalid or expired, run through the native client flow.
  storage = Storage('yt_partner_api.dat')
  credentials = storage.get()
  
  if (credentials is None or credentials.invalid or
      credentials.token_expiry <= datetime.now()):
    credentials = run(FLOW, storage)

مرحله 2c: شی httplib2 ایجاد کنید و اعتبارنامه ها را پیوست کنید

پس از اینکه کاربر اسکریپت ما را تأیید کرد، یک شی httplib2.Http ایجاد می کنیم که درخواست های API را مدیریت می کند و اعتبار مجوز را به آن شی متصل می کنیم.

عبارت import زیر را اضافه کنید:

  import httplib2

و این کد را به انتهای تابع main اضافه کنید:

  # Create httplib2.Http object to handle HTTP requests and
  # attach auth credentials.
  http = httplib2.Http()
  http = credentials.authorize(http)

مرحله 3: دریافت خدمات

تابع build کتابخانه کلاینت پایتون منبعی را می سازد که می تواند با یک API تعامل داشته باشد. پس از اینکه کاربر برنامه ما را مجاز کرد، شیء service را ایجاد می کنیم که روش هایی را برای تعامل با ContentOwnerService ارائه می دهد.

عبارت import زیر را اضافه کنید:

from apiclient.discovery import build

و این کد را در انتهای تابع main اضافه کنید:

  service = build("youtubePartner", "v1", http=http, static_discovery=False)
  contentOwnersService = service.contentOwners()

مرحله 4: یک درخواست API را اجرا کنید

اکنون یک درخواست سرویس ایجاد می کنیم و آن را اجرا می کنیم. کد زیر یک درخواست contentOwnersService.get() را ایجاد و اجرا می کند که اطلاعات مربوط به مالک محتوای مشخص شده را بازیابی می کند.

این کد را در انتهای تابع main اضافه کنید:

  # Create and execute get request.
  request = contentOwnersService.get(contentOwnerId=FLAGS.content_owner_id)
  content_owner_doc = request.execute(http)
  print ('Content owner details: id: %s, name: %s, '
         'notification email: %s') % (
              content_owner_doc['id'], content_owner_doc['displayName'],
              content_owner_doc['disputeNotificationEmails'])

برنامه کامل

این بخش برنامه کامل را با برخی از اطلاعات مجوز و نظرات اضافی در اسکریپت نشان می دهد. دو راه برای اجرای برنامه وجود دارد:

  • این دستور یک پنجره مرورگر راه اندازی می کند که از طریق آن می توانید در صورت لزوم احراز هویت کنید و به برنامه اجازه دهید درخواست های API را ارسال کند. اگر برنامه را مجاز کنید، اعتبارنامه ها به طور خودکار به اسکریپت بازگردانده می شوند.

    python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID.

    توجه: می‌توانید مقدار CONTENT_OWNER_ID را برای حساب خود در صفحه تنظیمات حساب در حساب CMS خود پیدا کنید. مقدار به عنوان Partner Code در بخش اطلاعات حساب در آن صفحه ذکر شده است.

  • این دستور یک URL را خروجی می دهد که می توانید آن را در مرورگر باز کنید و همچنین از شما می خواهد که یک کد مجوز را وارد کنید. وقتی به URL هدایت می‌شوید، آن صفحه به شما اجازه می‌دهد تا درخواست‌های API را از طرف شما ارسال کند. اگر آن مجوز را اعطا کنید، صفحه کد مجوزی را که باید برای تکمیل جریان مجوز وارد کنید، نمایش می‌دهد.

    python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID --noauth_local_webserver.

    توجه: ماژول oauth2client پارامتر noauth_local_webserver را تشخیص می دهد حتی اگر این پارامتر در اسکریپت ذکر نشده باشد.

client_secrets.json

 {
  "web": {
    "client_id": "INSERT CLIENT ID HERE",
    "client_secret": "INSERT CLIENT SECRET HERE",
    "redirect_uris": [],
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token"
  }
}

yt_partner_api.py

#!/usr/bin/python2.6
# -*- coding: utf-8 -*-
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Simple command-line sample for YouTube Content ID API.

Command-line application that retrieves the information
about given content owner.

Usage:
  $ python yt_partner_api.py --content_owner_id=[contentOwnerId]
  $ python yt_partner_api.py --content_owner_id=[contentOwnerId] --noauth_local_webserver

You can also get help on all the command-line flags the program understands
by running:

  $ python yt_partner_api.py --help

To get detailed log output run:

  $ python yt_partner_api.py --logging_level=DEBUG \
    --content_owner_id=[contentOwnerId]
"""

import gflags
import httplib2
import logging
import sys
import os

from datetime import *
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run

# Define flags. The gflags module makes it easy to define command-line options
# for an application. Run this program with the '--help' argument to see all
# of the flags that it understands.
FLAGS = gflags.FLAGS
gflags.DEFINE_string('content_owner_id', None, ('Required flag. '
     'Identifies the content owner id whose details are printed out.'))
gflags.MarkFlagAsRequired('content_owner_id')
gflags.DEFINE_enum('logging_level', 'ERROR',
    ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
    'Set the level of logging detail.')

  
def main(argv):
  # Let the gflags module process the command-line arguments
  try:
    argv = FLAGS(argv)
  except gflags.FlagsError, e:
    print '%s\nUsage: %s ARGS\n%s' % (e, argv[0], FLAGS)
    sys.exit(1)
  
  # Set the logging according to the command-line flag
  logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level))
  
  # Set up a Flow object to be used if we need to authenticate.
  FLOW = flow_from_clientsecrets('client_secrets.json',
      scope='https://www.googleapis.com/auth/youtubepartner',
      message='error message')

  # The Storage object stores the credentials. If the credentials are invalid
  # or expired and the script isn't working, delete the file specified below
  # and run the script again.
  storage = Storage('yt_partner_api.dat')
  credentials = storage.get()

  if (credentials is None or credentials.invalid or
      credentials.token_expiry <= datetime.now()):
    credentials = run(FLOW, storage)

  http = httplib2.Http()
  http = credentials.authorize(http)

  service = build("youtubePartner", "v1", http=http)
  contentOwnersService = service.contentOwners()

  # Create and execute get request.
  request = contentOwnersService.get(contentOwnerId=FLAGS.content_owner_id)
  content_owner_doc = request.execute(http)
  print ('Content owner details: id: %s, name: %s, '
         'notification email: %s') % (
              content_owner_doc['id'], content_owner_doc['displayName'],
              content_owner_doc['disputeNotificationEmails'])

if __name__ == '__main__':
  main(sys.argv)