開發人員指南:Python

YouTube Data API 可讓用戶端應用程式擷取並更新 Google Data API 資訊提供形式的 YouTube 內容。 您的用戶端應用程式可以使用 YouTube Data API 資訊提供,來擷取、搜尋及更新影片、評論、回應、播放清單、使用者設定檔和聯絡人,以及查詢符合特定條件的影片。

本文件除了提供 YouTube Data API 功能的相關背景外,也會提供透過 Python 用戶端程式庫與 API 互動的範例。如要使用 Python 用戶端程式庫,您必須使用 Python 2.0 以上版本,以及 Element Tree、httplib 和 urllib 模組。詳情請參閱依附元件模組

如果您在設定 Python 用戶端程式庫方面需要協助,請參閱入門指南。如要進一步瞭解 Python 用戶端程式庫與 YouTube 互動的基礎通訊協定,請參閱開發人員指南通訊協定頁面

關於這份文件

目標對象

本文件的適用對象為想使用 Python 用戶端程式庫與 YouTube 互動的用戶端應用程式。這個系列提供一系列的基本資料 API 互動範例。

如需 YouTube Data API 參考資料資訊,請參閱參考指南

本文假設您已瞭解 Google Data API 通訊協定的一般概念,也知道如何使用 Python 編寫程式。

如需 Python 類別和方法的參考資訊,請參閱原始碼內含的 pyDocs (適用於服務類別以及資料類別)。

文件結構

本文件包含以下章節:

  • 「驗證」一節提供兩種不同驗證方法,可將 API 操作與特定使用者帳戶建立關聯。另外,也會概述 YouTube Data API 和其他 Google Data API 的驗證差異。本文件中,特定 API 函式的說明將清楚指出該函式是否需要使用者進行驗證。一般而言,所有修改影片或動態饋給資料的要求都必須通過驗證。公開影片的唯讀要求不需要驗證。

  • 「瞭解影片動態消息與項目」一節提供 API 回應範例,並說明如何從影片或一系列搜尋結果中擷取單一影片的相關資訊。本節也會說明如何存取特定影片項目的中繼資料。最後,這個章節將說明個別影片更新的更新機制。

  • 擷取及搜尋影片一節將說明如何擷取特定的影片清單,例如 YouTube 最熱門的影片標準資訊提供。其他影片清單包括特定使用者上傳的影片,以及與特定影片相關的影片清單。本節也說明如何使用這個 API,讓使用者透過特定搜尋字詞或類別搜尋 YouTube 的影片庫。

  • 「上傳影片」一節將簡單說明兩種方式,讓您允許使用者透過應用程式將影片上傳至 YouTube。此外,本節也會說明如何上傳影片以回應其他影片。

  • 更新及刪除影片」一節說明如何使用 API 更新 YouTube 影片的相關資訊。以及如何使用 API 移除影片。

  • 「使用社群功能」一節說明的 API 函式,可讓使用者與 YouTube 影片互動。這類函式會說明如何在現有影片中張貼評分、留言或申訴。您也可以使用 API 擷取影片留言清單。

  • 「儲存及收集影片」一節將說明如何使用 API 存取、建立及更新您喜愛的影片、影片播放清單和 YouTube 頻道的訂閱內容。並且說明如何透過新增及移除影片來修改影片播放清單與最愛。

  • 啟用使用者互動」一節將說明如何使用 API 擷取及更新使用者個人資料。本節也說明如何擷取、新增、更新及刪除使用者聯絡人。

開始說明

需求條件

您的用戶端應用程式可以使用 YouTube Data API 資訊提供,來搜尋、擷取與更新影片、評論、回應、播放清單、訂閱、使用者設定檔等等。

本文件除了提供 YouTube Data API 功能的相關背景外,也會提供透過 Python 用戶端程式庫與 API 互動的範例。如要使用 Python 用戶端程式庫,您需要 Python 2.2 以上版本,以及 Element Tree、httplib 和 urllib 模組。詳情請參閱依附元件模組

要進一步瞭解如何設定環境,請參閱入門指南。如要進一步瞭解 Python 用戶端程式庫與 YouTube 互動的基礎通訊協定,請參閱開發人員指南通訊協定頁面

您可以將下方程式碼範例的程式碼片段複製/貼到程式碼中,然後根據需求進行修改。

您必須先初始化 gdata.youtube.service.YouTubeService 物件,才能透過 YouTube Data API 執行任何作業。下列 import 陳述式會自動從 gdata.mediagdata.geo 模組執行進一步匯入作業。請注意,除了擷取公開內容之外,所有動作都必須經過驗證

import gdata.youtube
import gdata.youtube.service

yt_service = gdata.youtube.service.YouTubeService()

# Turn on HTTPS/SSL access.
# Note: SSL is not available at this time for uploads.
yt_service.ssl = True

本指南中的大多數方法範例都是在 gdata.youtube.service.YouTubeService 的執行個體上運作。測試來自互動式 Python 解譯器的未經驗證要求可能有所助益。

注意:您必須正確新增 Python 用戶端程式庫中的路徑。請務必執行我們提供的 setup.py 指令碼,然後加以安裝。詳情請參閱入門指南

驗證

Python 用戶端程式庫可用於公開或私人資訊提供。公開資訊提供是唯讀的,不需要進行驗證。私人動態饋給要求您必須驗證 YouTube 伺服器。

您可以透過 ClientLogin 驗證 (電腦版應用程式) 或 AuthSub 驗證 (網頁應用程式) 進行驗證。

設定開發人員金鑰和用戶端 ID

開發人員金鑰可識別提交 API 要求的 YouTube 開發人員。用戶端 ID 可識別您的應用程式,以便進行記錄及偵錯。

使用 Python 用戶端程式庫提出 API 要求時,系統會使用 X-GData-Key 要求標頭來指定您的開發人員金鑰,而 X-GData-Client 標頭則用於指定用戶端 ID。無論目前使用的驗證配置為何,您可以在 YouTubeService 物件上設定開發人員金鑰和用戶端 ID:

yt_service.developer_key = 'ABCxyz123...'
yt_service.client_id = 'My-Client_id'

您必須申請 YouTube 開發人員金鑰。

網路應用程式的 AuthSub 驗證

網路應用程式需要使用 AuthSub Proxy 驗證,需要透過 YouTube/Google 帳戶驗證使用者身分的使用者。操作者不需要存取 YouTube 使用者的使用者名稱和密碼,只需要一組特殊的 AuthSub 憑證。

使用者初次造訪您的應用程式時,尚未經過 Google 服務驗證。在這種情況下,您必須提供連結,引導使用者向 Google 授權應用程式存取其 YouTube 帳戶的要求。Python 用戶端程式庫提供了用於產生此網址的函式。以下程式碼會設定「AuthSubRequest」頁面的連結。

def GetAuthSubUrl():
  next = 'http://www.example.com/video_upload.pyc'
  scope = 'http://gdata.youtube.com'
  secure = False
  session = True

yt_service = gdata.youtube.service.YouTubeService()
return yt_service.GenerateAuthSubURL(next, scope, secure, session)

authSubUrl = GetAuthSubUrl()
print '<a href="%s">Login to your Google account</a>' % authSubUrl

請注意傳送至服務物件的 GenerateAuthSubURL 方法的參數:

  • next:YouTube 會在使用者授權應用程式存取帳戶後,將他們重新導向的網頁網址。
  • scope:表示應用程式只可存取 YouTube API 資訊提供。
  • secure:指出傳回的權杖並非安全權杖。
  • session:代表這個憑證可交換為多用途 (工作階段) 憑證。

傳回的網址看起來會像這樣:

https://www.google.com/accounts/AuthSubRequest?scope=http%3A%2F%2Fgdata.youtube.com&session=1&secure=0&next=http%3A%2F%2Fwww.example.com%2Fvideo_upload.pyc

使用者隨後點選連結即可登入自己的 YouTube 帳戶。使用者授權您的應用程式存取自己的帳戶後,系統就會將他們重新導向回 next 網址。該網址的單次使用權杖值會附加為查詢參數。網址格式如下:

http://www.example.com/video_upload.pyc?token=Abc123...

下一節將示範如何升級這個憑證。以下程式碼片段示範如何從網址擷取這個憑證:

import cgi
parameters = cgi.FieldStorage()
authsub_token = parameters[[]'token' ]

升級為工作階段符記

基於安全考量,這個憑證只能使用一次,因此你必須將這個工作階段的單次使用憑證換成工作階段憑證。如要瞭解這項程序,請參閱 AuthSub 說明文件。下列程式碼片段說明如何升級憑證。

yt_service = gdata.youtube.service.YouTubeService()
yt_service.SetAuthSubToken(authsub_token)
yt_service.UpgradeToSessionToken()

這個權杖值代表一次性的 AuthSub 權杖。如上指定了 session = True,這個權杖可使用 UpgradeToSessionToken 方法交換這個 AuthSub 工作階段符記,以呼叫 AuthSubSessionToken 服務。

您的 YouTubeService 物件現已通過驗證,可用於透過 YouTube API 執行後續的所有要求。除非你明確發出撤銷憑證的要求,或是使用者造訪其 YouTube 帳戶的「授權網站」頁面,並決定撤銷存取權限,否則 AuthSub 工作階段憑證並不會過期。

安裝版應用程式的 ClientLogin 驗證

ClientLogin 驗證是在已安裝的應用程式中使用,可以儲存或查詢使用者的使用者名稱和密碼。如要使用這種驗證方式,請叫用 gdata.service.GDataService 類別沿用的 YouTubeServiceProgrammaticLogin 方法,指定代表用戶端將要求傳送給驗證使用者的 ID 和密碼。

yt_service = gdata.youtube.service.YouTubeService()
yt_service.email = 'jo@gmail.com'
yt_service.password = 'mypassword'
yt_service.source = 'my-example-application'
yt_service.ProgrammaticLogin()

憑證設定完成後,可使用 YouTubeService 物件來處理所有後續的要求。如要對 YouTube API 執行上傳和任何類型的「寫入」要求 (新增註解等),請務必在執行驗證時,將開發人員金鑰和用戶端 ID 傳遞至 yt_service 物件:

# A complete client login request
yt_service.email = 'jo@gmail.com'
yt_service.password = 'mypassword'
yt_service.source = 'my-example-application'
yt_service.developer_key = 'ABC123...'
yt_service.client_id = 'my-example-application'
yt_service.ProgrammaticLogin()

設定 developer_keyclient_id 屬性時,YouTubeService 物件會自動設定正確的 X-GData-KeyX-GData-Client 標頭。

注意:如要進一步瞭解 AuthSub 和 ClientLogin 機制,請參閱 Google Data API 驗證說明文件

瞭解影片資訊提供與項目

YouTube Data API 提供數種影片資訊提供,可代表影片清單,例如標準資訊提供、上傳、訂閱和最愛。請參閱參考指南,瞭解每個動態饋給的網址。

顯示影片資訊提供

YouTube API 中的許多資訊提供包含影片項目。這些動態饋給大多可以建模為 gdata.youtube.YouTubeVideoFeed 物件,每個物件都包含多個 gdata.youtube.YouTubeVideoEntry 物件。每個影片項目都只能對應至一個 YouTube 影片,其中包含影片的相關資訊。

擷取影片清單的基本結構,就是建立影片資訊提供的網址,然後一次處理一個項目,類似於以下程式碼:

def GetAndPrintVideoFeed(uri):
  yt_service = gdata.youtube.service.YouTubeService()
  feed = yt_service.GetYouTubeVideoFeed(uri)
  for entry in feed.entry:
    PrintEntryDetails(entry) # full documentation for this function

擷取及搜尋影片」部分詳細說明瞭常見的資訊提供網址,以及如何擷取各種影片資訊提供。

擷取特定影片項目

如果您知道特定影片項目的資訊,可以只擷取其 ID。項目網址是以影片 ID 為依據:

http://gdata.youtube.com/feeds/api/videos/videoID

下列程式碼會擷取與 YouTube 影片相對應的 gdata.youtube.YouTubeVideoEntry

entry = yt_service.GetYouTubeVideoEntry(video_id='the0KZLEacs')

影片項目內容

可從 gdata.youtube.YouTubeVideoEntry 物件中擷取多種中繼資料,例如縮圖、播放器網址和影片時間長度。以下程式碼示範如何取得其中一些資訊。Python 用戶端程式庫會將 XML 元素對應至類別,藉此抽像大部分的功能。有關項目YouTubeVideoEntry項目的重要資訊,可從項目 (代表 XML media:group 元素) 的 media 屬性 (包含 gdata.media.Group 物件) 中取得。以下是擷取影片中繼資料的方法範例:

def PrintEntryDetails(entry):
  print 'Video title: %s' % entry.media.title.text
  print 'Video published on: %s ' % entry.published.text
  print 'Video description: %s' % entry.media.description.text
  print 'Video category: %s' % entry.media.category[[]0].text
  print 'Video tags: %s' % entry.media.keywords.text
  print 'Video watch page: %s' % entry.media.player.url
  print 'Video flash player URL: %s' % entry.GetSwfUrl()
  print 'Video duration: %s' % entry.media.duration.seconds

  # non entry.media attributes
  print 'Video geo location: %s' % entry.geo.location()
  print 'Video view count: %s' % entry.statistics.view_count
  print 'Video rating: %s' % entry.rating.average

  # show alternate formats
  for alternate_format in entry.media.content:
    if 'isDefault' not in alternate_format.extension_attributes:
      print 'Alternate format: %s | url: %s ' % (alternate_format.type,
                                                 alternate_format.url)

  # show thumbnails
  for thumbnail in entry.media.thumbnail:
    print 'Thumbnail url: %s' % thumbnail.url

注意:如要進一步瞭解如何產生在網頁中嵌入播放器的必要資訊,請參閱通訊協定指南

擷取及搜尋影片

擷取標準資訊提供

YouTube Data API 提供 YouTube 最熱門的影片標準資訊提供,這個 API 先前支援其他標準動態饋給,但該動態饋給現已淘汰。詳情請參閱開發人員指南

YouTube 最熱門的影片資訊提供網址格式如下:

http://gdata.youtube.com/feeds/api/standardfeeds/most_popular

注意事項:您也可以按照下列格式指定語言代碼 ID,以擷取特定語言代碼的標準動態饋給:http://gdata.youtube.com/feeds/api/standardfeeds/localeID/feedID。例如,日本最熱門的影片就是:http://gdata.youtube.com/feeds/api/standardfeeds/JP/most_popular。如需假設語言代碼的 ID 完整清單,請參閱參考指南

def PrintVideoFeed(feed):
  for entry in feed.entry:
    PrintEntryDetails(entry)

def GetAndPrintFeedByUrl:
  yt_service = gdata.youtube.service.YouTubeService()

  # You can retrieve a YouTubeVideoFeed by passing in the URI
  uri = 'http://gdata.youtube.com/feeds/api/standardfeeds/JP/most_popular'
  PrintVideoFeed(yt_service.GetYouTubeVideoFeed(uri))

擷取特定使用者上傳的影片

每位 YouTube 使用者都有相關聯的影片動態消息,並對應到 http://gdata.youtube.com/feeds/api/users/username/uploads 所上傳的影片。以下程式碼示範如何擷取及顯示使用者上載的資訊提供:

def GetAndPrintUserUploads(username):
  yt_service = gdata.youtube.service.YouTubeService()
  uri = 'http://gdata.youtube.com/feeds/api/users/%s/uploads' % username
  PrintVideoFeed(yt_service.GetYouTubeVideoFeed(uri))

注意:您也可以改用「default」字串取代 username,以擷取目前已驗證使用者的影片。

如要擷取相關影片,請將 gdata.youtube.YouTubeVideoEntry 物件的影片 ID 傳遞至 gdata.youtube.service.YouTubeService 物件的 GetYouTubeRelatedVideoFeed 方法。這會擷取包含相關項目的 YouTubeVideoFeed 物件。

related_feed = yt_service.GetYouTubeRelatedVideoFeed(video_id='abc123')

搜尋影片

您可以利用 YouTube Data API 要求一組符合特定條件的項目,例如要求特定作者所發布的影片項目、使用影片格式或包含特定關鍵字。為此,您可以使用特定搜尋條件建立 gdata.service.YouTubeVideoQuery 物件,並將其傳送到 gdata.youtube.service.YouTubeServiceYouTubeQuery 方法。

下列範例說明如何執行搜尋查詢,並依觀看次數排序,包含受限制的影片 (在 API 中稱為「Racy」):

def SearchAndPrint(search_terms):
  yt_service = gdata.youtube.service.YouTubeService()
  query = gdata.youtube.service.YouTubeVideoQuery()
  query.vq = search_terms
  query.orderby = 'viewCount'
  query.racy = 'include'
  feed = yt_service.YouTubeQuery(query)
  PrintVideoFeed(feed)

gdata.service.Query 類別和子類別 (例如 YouTubeVideoQuery) 負責建構動態饋給網址。上述的 VideoQuery 建構一個具有類似以下項目的網址:

http://gdata.youtube.com/feeds/api/videos?vq=<searchTerms>&racy=include&orderby=viewCount

以下列舉設定 搜尋參數的幾個常見 YouTubeVideoQuery 屬性:

author
設定項目的作者。作者等同於 YouTube 使用者名稱,
format
指定影片格式。接受數字參數,以指定用於行動版影片播放的兩種 RTSP 串流網址之一,或為嵌入式 Flash 播放器指定 HTTP 網址。
racy
指出是否要將限制內容納入結果。只接受兩個參數:「include」或「exclude」。
max_results
設定一次可傳回的項目數量上限。
start_index
設定要擷取的第一個結果以 1 為基礎的索引 (用於分頁)。
orderby
設定列出項目的順序,例如以 relevanceviewCountpublishedrating 排列。
time
設定時間範圍,將標準資訊提供的結果限制在 todaythis_weekthis_monthall_time 範圍內。
vq
設定搜尋查詢字詞。搜尋所有影片中繼資料中的指定字串,例如標題、標記和說明。

注意:如要進一步瞭解查詢參數,請參閱 YouTube Data API 參考指南Google Data API 參考指南

使用類別和關鍵字進行搜尋

您可以限制搜尋結果,只顯示符合一組類別和關鍵字的影片。參考指南說明如何指定 YouTube 預先定義的類別 (例如「音樂」、「人物與網誌」等) 和使用者定義的關鍵字 (標記)。

以下程式碼示範如何將搜尋字詞變更為「小寫」,以使用關鍵字 (標記) 進行搜尋。注意: 有些字詞 (例如「喜劇」) 可以是 YouTube 類別以及關鍵字,所以類別和關鍵字查詢使用慣例,「大寫字詞」表示 YouTube 類別,而短字 (「喜劇」) 表示關鍵字。

def SearchAndPrintVideosByKeywords(list_of_search_terms):
  yt_service = gdata.youtube.service.YouTubeService()
  query = gdata.youtube.service.YouTubeVideoQuery()
  query.orderby = 'viewCount'
  query.racy = 'include'
  for search_term in list_of_search_terms:
    new_term = search_term.lower()
    query.categories.append('/%s' % new_term)
  feed = yt_service.YouTubeQuery(query)
  PrintVideoFeed(feed)

搜尋開發人員標記

開發人員標記是隱藏的額外關鍵字,開發人員可能會用來標記使用者透過應用程式上傳的內容。上傳時,開發人員標記會與標頭中所設定的開發人員金鑰相符。這些關鍵字不會公開顯示,也可用來擷取影片。如要依據特定開發人員標記搜尋影片,請使用您的開發人員金鑰傳送一般的 YouTube Data API 搜尋要求。請務必指定影片所屬的類別架構和開發人員標記。您可以前往下列網址擷取與開發人員標記相符的影片資訊提供 (在此範例中為「your_tag_here」)。

developer_tag_uri = 'http://gdata.youtube.com/feeds/videos/-/%7Bhttp%3A%2F%2Fgdata.youtube.com%2Fschemas%2F2007%2Fdevelopertags.cat%7Dyour_tag_here'
yt_service = gdata.youtube.service.YouTubeService()
PrintVideoFeed(yt_service.GetYouTubeVideoFeed(developer_tag_uri))

上傳影片

請務必參閱通訊協定指南中的圖表,大致瞭解上傳程序。你可以透過以下兩種方式上傳影片:

  • 您可以直接上傳伺服器中的影片
  • 或是先傳送中繼資料,再請使用者透過「瀏覽器」上傳方式

直接上傳

如要上傳影片,您必須先建立新的 gdata.youtube.YouTubeVideoEntry 物件,並將含有必要中繼資料的 gdata.media.Group 物件傳遞給該物件。以下範例說明如何將 Quicktime 影片「mytestmovies.mov」上傳到 YouTube,並使用下列屬性:

屬性
名稱我的測試電影
Category (類別)自動
關鍵字汽車, 有趣
說明我的說明
檔案名稱mytestmovies.mov
檔案 MIME 類型影片/quicktime
影片是私人影片?
影片位置37,-122 (lat,long)
開發人員廣告代碼mydevelopertag、otherdevelopertag

以下程式碼會建立要上傳的空白 YouTubeVideoEntryInsertVideoEntry 方法 YouTubeService 要求下列參數:

  • video_entry — 包含中繼資料的 gdata.youtube.VideoEntry 物件
  • filename_or_handle:檔案型物件或用來讀取影片的檔案名稱
  • youtube_username - 選用字串,用來指定要將影片上傳到哪個帳戶。您的帳戶需要取得適當的權限。這會預設為目前通過驗證的使用者帳戶。
  • content_type:選用字串,用來指定要上傳影片的 MIME 類型。
請注意,這些範例假設 yt_service 變數參照了完整驗證的 YouTubeService 物件。

# prepare a media group object to hold our video's meta-data
my_media_group = gdata.media.Group(
  title=gdata.media.Title(text='My Test Movie'),
  description=gdata.media.Description(description_type='plain',
                                      text='My description'),
  keywords=gdata.media.Keywords(text='cars, funny'),
  category=[[]gdata.media.Category(
      text='Autos',
      scheme='http://gdata.youtube.com/schemas/2007/categories.cat',
      label='Autos')],
  player=None
)


# prepare a geo.where object to hold the geographical location
# of where the video was recorded
where = gdata.geo.Where()
where.set_location((37.0,-122.0))

# create the gdata.youtube.YouTubeVideoEntry to be uploaded
video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group,
                                              geo=where)

# set the path for the video file binary
video_file_location = '/path/to/my/file.mov'

new_entry = yt_service.InsertVideoEntry(video_entry, video_file_location)

如果我們想要利用選用的開發人員標記來標記影片 (請參閱搜尋開發人員標記以瞭解更多資訊),那麼在呼叫 InsertVideoEntry 之前,我們可以使用 AddDeveloperTags 方法:

developer_tags = [[]'some_tag_01', 'another_tag']
video_entry.AddDeveloperTags(developer_tags)

注意:如要以私人方式上傳影片,您必須將私人屬性傳送至 gdata.media.Group

my_media_group = gdata.media.Group(
  title=gdata.media.Title(text='My Test Movie'),
  description=gdata.media.Description(description_type='plain',
                                      text='My description'),
  keywords=gdata.media.Keywords(text='cars, funny'),
  category=[[]gdata.media.Category(
      text='Autos',
      scheme='http://gdata.youtube.com/schemas/2007/categories.cat',
      label='Autos')],
  player=None,
  private=gdata.media.Private()
)

video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group)

# assuming that video_file_location points to a valid path
new_entry = yt_service.InsertVideoEntry(video_entry, video_file_location)

以瀏覽器為基礎的上傳功能

以瀏覽器為基礎的上傳程序幾乎與直接上傳相同,差別在於,您未於檔案中繼資料內的要求中,上載檔案二進位檔。而是只建立只包含中繼資料的 YouTubeVideoEntry。然後,於 YouTube API 伺服器上發布此影片項目至特別連結。XML 回應包含 tokenurl,可用來使用標準 HTML 表單上傳二進位檔案。

# create media group as usual
my_media_group = gdata.media.Group(
  title=gdata.media.Title(text='My Test Movie'),
  description=gdata.media.Description(description_type='plain',
                                      text='My description'),
  keywords=gdata.media.Keywords(text='cars, funny'),
  category=[[]gdata.media.Category(
      text='Autos',
      scheme='http://gdata.youtube.com/schemas/2007/categories.cat',
      label='Autos')],
  player=None
)

# create video entry as usual
video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group)

# upload meta data only
response = yt_service.GetFormUploadToken(video_entry)

# parse response tuple and use the variables to build a form (see next code snippet)
post_url = response[[]0]
youtube_token = response[[]1]

上述程式碼會輸出連結和憑證,用來建立要顯示在使用者瀏覽器中的 HTML 表單。以下提供一個簡單的範例表單,其中 youtube_token 代表傳回的權杖元素內容,如上方 YouTubeVideoEntry 擷取而來。提交表格之後,為了將使用者重新導向到您的網站,請務必將 next 參數附加到 post_url (如下所示),該運作方式與 AuthSub 連結的 next 參數相同。唯一的差別在於,系統會將 statusid 變數做為網址參數傳回,而非單一使用的權杖。

next = 'http://example.com/post_video_upload.pyc'

form = """<form action="%s?nexturl=%s" method="post" enctype="multipart/form-data">
          <input name="file" type="file"/>
          <input name="token" type="hidden" value="%s"/>
          <input value="Upload Video File" type="submit" />
          </form>""" % (post_url, next, youtube_token)

成功上傳的回應應如下所示:

http://example.com/post_video_upload.pyc?status=200&id=ABC123

status 參數會傳回上傳交易的 HTTP 交易狀態。id 參數會傳回指派給上傳影片的 YouTube 影片 ID。

正在檢查上傳狀態

影片上傳完畢後,將立即顯示在已驗證使用者的上傳內容中。但在網站處理完畢之前,將不會對外公開。遭到拒絕或無法成功上傳的影片,只會顯示在已驗證使用者的上傳影片的資訊提供中。下列程式碼會檢查 YouTubeVideoEntry 的狀態,確認其是否尚未上線,或者是遭到拒絕。

upload_status = yt_service.CheckUploadStatus(new_entry)

if upload_status is not None:
  video_upload_state = upload_status[[]0]
  detailed_message = upload_status[[]1]

更新及刪除影片

更新影片資訊

如要更新影片中繼資料,只要更新 YouTubeVideoEntry 物件,然後使用 YouTubeService 物件的 UpdateVideoEntry 方法即可。這個方法使用 YouTubeVideoEntry 做為參數,其中包含更新過的中繼資料。

# assuming we have a video entry that was just posted in our 'new_entry' variable
new_entry.media.title.text = 'My Updated Video Title'
new_entry.media.description.text = 'Just updated'

updated_entry = yt_service.UpdateVideoEntry(new_entry)

刪除影片

刪除影片非常簡單,只需要呼叫 YouTubeService 物件的 DeleteVideoEntry 即可。

response = yt_service.DeleteVideoEntry(entry_to_be_deleted)

if response:
  print 'Video successfully deleted!'

使用社群功能

新增評分

如要評估影片評分,請使用 YouTubeService 物件的 AddRating 方法。請注意,您無法為自己的影片評分,而且您的評分必須在 1 至 5 (含) 之間:

video_id_to_rate = 'Ncakifd_16k'
video_entry = yt_service.GetYouTubeVideoEntry(video_id=video_id_to_rate)
response = yt_service.AddRating(3, video_entry)

留言

擷取影片留言

只要有 YouTubeVideoEntry 物件或簡單的影片 ID,您就能使用 YouTubeService 物件的 GetYouTubeVideoCommentFeed 方法,擷取並列印含有影片留言的資訊提供。產生的動態饋給是一個由 gdata.youtube.YouTubeCommentEntry 物件組成的 gdata.youtube.YouTubeCommentFeed。動態饋給可以像任何其他資訊提供一樣進行剖析:

video_id = 'ABC123...'
comment_feed = yt_service.GetYouTubeVideoCommentFeed(video_id=video_id)

for comment_entry in comment_feed.entry:
  print comment_entry.ToString()

新增意見

如要新增註解,請使用 YouTubeService 物件的 AddComment 方法。此方法需要可加註的完整 YouTubeVideoEntry 物件,以及代表註解的字串:

my_comment = 'what a boring test video'
video_id = '9g6buYJTt_g'
video_entry = yt_service.GetYouTubeVideoEntry(video_id=video_id)
yt_service.AddComment(comment_text=my_comment, video_entry=video_entry)

影片回應

YouTube 影片回應是與另一部影片相關的影片回應。影片回應功能已按照這份公告所述。雖然現有的影片回應仍可使用,但 YouTube 不再支援擷取影片回應清單、上傳新的影片回應或刪除影片回應,但您可以刪除影片回應中所使用的影片。因此,API 也不再支援這些函式。

影片回應作業的 API 要求現在會傳回下列資料:

  • 為影片擷取影片回應的要求,將會傳回空白的清單。
  • 新增影片回應的要求會傳回 403 HTTP 回應代碼。
  • 刪除影片回應的要求會傳回 403 HTTP 回應代碼。

檢舉影片

您可以使用 YouTubeService 物件的 AddComplaint 方法,對影片新增申訴。申訴書必須是有效的類別。詳情請參閱通訊協定指南中的「新增申訴」一節。

video_id_to_flag = 'Ncakifd_16k'
complaint_term = 'VIOLENCE'
complaint_text = ('Please ignore this complaint. '
                  'I\'m testing a YouTube API and needed to issue '
                  'a complaint to test the add complaint function. ')

response = yt_service.AddComplaint(complaint_text, complaint_term, video_id_to_flag)

儲存和收集影片

收藏的影片

擷取使用者最愛的影片

YouTube 使用者可以選擇將自己觀賞的影片標示為最愛項目。使用者常用的資訊提供一般地點如下:

http://gdata.youtube.com/feeds/api/users/username/favorites

如要擷取使用者喜愛的影片,請使用 YouTubeService 物件的 GetUserFavoritesFeed 方法。此方法使用選用字串做為參數,代表要擷取使用者所最愛的資訊提供的 YouTube 使用者名稱。

favorite_feed = yt_service.GetUserFavoritesFeed(username='gdpython')

傳回的動態饋給是一般的影片動態饋給,內含 YouTubeVideoEntry 物件。

注意:您也可以傳遞 default 字串,為目前已通過驗證的使用者擷取最愛項目。如果未提供使用者名稱,則這是 GetUserFavoritesFeed 方法的預設行為。

正在新增常用聯絡人

如要新增喜愛的影片,請使用 YouTubeService 物件的 AddVideoEntryToFavorites 方法。參數是您要新增的 YouTubeVideoEntry,以及要新增之人員的使用者名稱 (預設為目前驗證的使用者)。

video_id = 'Ncakifd_16k'
video_entry = yt_service.GetYouTubeVideoEntry(video_id=video_id)
response = yt_service.AddVideoEntryToFavorites(video_entry)

# The response, if successfully posted is a YouTubeVideoEntry
if isinstance(response, gdata.youtube.YouTubeVideoEntry):
  print 'Video successfully added to favorites'

刪除我的最愛

如要刪除常用項目,只要使用 YouTubeService 物件的 DeleteVideoEntryFromFavorites 方法即可。

video_id = 'Ncakifd_16k'
response = yt_service.DeleteVideoEntryFromFavorites(video_id)
if response is True:
  print 'Video deleted from favorites'

播放清單

每位 YouTube 使用者都有一個播放清單,其中含有使用者建立的所有播放清單。而每個播放清單都有一份資訊提供,其中收錄了其中的所有影片。

擷取使用者播放清單

如要手動擷取使用者所有播放清單的清單,請使用下列網址:

http://gdata.youtube.com/feeds/api/users/username/playlists

使用 Python 用戶端程式庫時,您可以使用 YouTubeService 物件的 GetYouTubePlaylistFeed 方法:

playlist_feed = yt_service.GetYouTubePlaylistFeed(username='gdpython')

# instead of passing in a username, you can also pass the URI to the playlist feed:
playlist_feed = yt_service.GetYouTubePlaylistFeed(uri='http://gdata.youtube.com/feeds/api/users/default/playlists')

注意:您也可以傳遞 'default' 字串來參照目前已通過驗證的使用者,而不是傳遞特定使用者名稱 (例如上例中的「gdpython」)。

gdata.youtube.YouTubePlaylistFeed 代表 gdata.youtube.YouTubePlaylistEntry 物件的資訊提供。這是指使用者可能有的個別播放清單。特定播放清單的影片項目會以 gdata.youtube.YouTubePlaylistVideoEntry 物件表示。這些物件與一般 gdata.youtube.YouTubeVideoEntry 物件非常類似,但仍有一些例外。自訂標題和說明可以套用至影片,位置欄位則代表影片在播放清單中的位置。

擷取播放清單資訊

針對 YouTubePlaylistEntry (代表特定播放清單),您可以取得內含 YouTubePlaylistVideoEntry 物件的 YouTubePlaylistVideoFeed。如上所述,這些物件代表播放清單中的個別影片 (包含自訂的自訂標題和說明)。只要將播放清單的 URI 傳送至 YouTubeService 物件的 GetYouTubePlaylistVideoFeed 方法,即可取得這個資訊提供:

# a typical playlist URI
playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505'

playlist_video_feed = yt_service.GetYouTubePlaylistVideoFeed(uri=playlist_uri)

# iterate through the feed as you would with any other
for playlist_video_entry in playlist_video_feed.entry:
  print playlist_video_entry.title.text

新增播放清單

如要新增播放清單,只要使用 YouTubeService 物件的 AddPlaylist 方法即可。此方法使用的參數如下:playlist_title、playlist_description (字串) 和可設為布林值 (True) 的播放清單。

new_public_playlistentry = yt_service.AddPlaylist('my new playlist', 'a new playlist')

if isinstance(new_public_playlistentry, gdata.youtube.YouTubePlaylistEntry):
  print 'New playlist added'

# adding a private playlist
new_private_playlistentry = yt_service.AddPlaylist('new private playlist', 'a new private playlist', True)

if isinstance(new_private_playlistentry, gdata.youtube.YouTubePlaylistEntry):
  print 'New private playlist added'

更新播放清單

如要更新播放清單,請使用 YouTubeService 物件的 UpdatePlaylist 方法。方法使用的參數如下:待更新播放清單的編號、新標題、新的說明、將播放清單設為私人播放清單的選用布林值,以及可指出播放清單擁有使用者名稱的選用字串。該字串將預設為目前通過驗證的使用者。

# here we are updating a public playlist with a new title while also making it private

# we assume that playlist_to_be_updated here represents a YouTubePlaylistEntry object
playlist_entry_id = playlist_to_be_updated.id.text.split('/')[[]-1]

# we want to keep the original description for the playlist so we store it first
original_description = playlist_to_be_updated.description.text

updated_playlist = yt_service.UpdatePlaylist(playlist_entry_id,
                                             'a new updated title',
                                             original_playlist_description,
                                             playlist_private=True)

將影片新增至播放清單

您可以使用 YouTubeService 物件的 AddPlaylistVideoEntryToPlaylist 方法,將影片新增至播放清單。下列程式碼會將影片新增到播放清單,並附上自訂標題和說明。

custom_video_title = 'my test video on my test playlist'
custom_video_description = 'this is a test video on my test playlist'
video_id = 'Ncakifd_16k'
playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505'

playlist_video_entry = yt_service.AddPlaylistVideoEntryToPlaylist(
    playlist_uri, video_id, custom_video_title, custom_video_description)

if isinstance(playlist_video_entry, gdata.youtube.YouTubePlaylistVideoEntry):
  print 'Video added'

注意:您不一定要自訂標題和說明,但如果未指定,系統會使用影片的實際標題和說明。

編輯播放清單中的影片資訊

使用 YouTubeService 物件的 UpdatePlaylistVideoEntryMetaData 方法變更 YouTubePlaylistVideoEntry 的中繼資料。在以下範例中,我們決定為新的影片加上標題並移至播放清單中的第一個位置 (位置 1)。

playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505'
playlist_entry_id = 'B0F29389E537F888'

new_video_title = 'a useful video'
new_video_description = 'updated video description'

updated_playlist_video_entry = yt_service.UpdatePlaylistVideoEntryMetaData(
    playlist_uri, playlist_entry_id, new_video_title, new_video_description, 1)

注意:如要將播放清單中的影片標題和標題還原為原始的中繼資料,只需在 NULL 中傳遞標題和說明即可。

從播放清單中移除影片

如要移除播放清單中的影片,請使用 YouTubeService 物件的 DeletePlaylistVideoEntry 方法。此方法需要刪除含有該項目的播放清單的 URI 以及項目的 ID:

playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505'
playlist_entry_id = 'B0F29389E537F888'
response = yt_service.DeletePlaylistVideoEntry(playlist_uri,
                                               playlist_entry_id)
if response is True:
  print 'Entry successfully deleted'

刪除播放清單

如要刪除播放清單,只要使用 YouTubeService 物件的 DeletePlaylist 方法,傳入要刪除的播放清單的 URI 即可:

playlist_uri = 'http://gdata.youtube.com/feeds/api/playlists/BCB3BB96DF51B505'
response = yt_service.DeletePlaylist(playlist_uri)

if response is True:
  print 'Playlist successfully deleted'

訂閱項目

如要擷取特定使用者訂閱的頻道、搜尋和最愛清單,請使用下列 URI:

http://gdata.youtube.com/feeds/api/users/username/subscriptions

注意:您也可以傳遞 default 字串,為目前已通過驗證的使用者擷取最愛項目。

擷取使用者訂閱項目

以下程式碼示範如何擷取和列印特定使用者的訂閱清單。訂閱項目是以包含 gdata.youtube.YouTubeSubscriptionEntry 物件的 gdata.youtube.YouTubeSubscriptionFeed 表示。如要擷取訂閱項目,請使用 YouTubeService 物件的 GetYouTubeSubscriptionFeed 方法,傳入訂閱資訊提供的 URI 或要擷取訂閱資訊提供的使用者名稱。使用者名稱參數預設為已驗證的使用者。

subscription_feed = yt_service.GetYouTubeSubscriptionFeed(username='gdpython')

if isinstance(subscription_feed, gdata.youtube.YouTubeSubscriptionFeed)):
  # given a YouTubeSubscriptionEntry we can determine it's type (channel, favorite, or query)
  for entry in subscription_feed.entry:
    print entry.GetSubscriptionType()

新增訂閱

您可以在已驗證使用者的「訂閱內容」動態消息中插入新的 YouTubeSubsciptionEntry,藉此建立新的訂閱項目。我們可以建立三種類型的訂閱:透過 AddSubscriptionToChannel 訂閱使用者的頻道、訂閱使用者最愛 (使用 AddSubscriptionToFavorites 或訂閱特定關鍵字 (使用 AddSubscriptionToQuery) 等程式碼。

new_subscription = yt_service.AddSubscriptionToChannel(
      username_to_subscribe_to='GoogleDevelopers')

if isinstance(new_subscription, gdata.youtube.YouTubeSubscriptionEntry):
  print 'New subscription added'

您也可以訂閱「GoogleDevelopers」使用者最愛的項目:

new_subscription = yt_service.AddSubscriptionToFavorites(
    username='GoogleDevelopers')
if isinstance(new_subscription, gdata.youtube.YouTubeSubscriptionEntry):
  print 'New subscription added'

最後,你也可以訂閱特定的搜尋字詞。我們訂閱了以「python」標記的影片查詢。

new_subscription = yt_service.AddSubscriptionToQuery(query='python')

if isinstance(new_subscription, gdata.youtube.YouTubeSubscriptionEntry):
  print 'New subscription added'

刪除訂閱項目

如要刪除使用者訂閱項目,請使用 YouTubeService 物件的 DeleteSubscription 方法。

sample_subscription_uri = ('http://gdata.youtube.com/feeds/api/users/'
                           'gdpython/subscriptions/c0c77ca6102a7479')

response = yt_service.DeleteSubscription(sample_subscription_uri)

if response is True:
  print 'Subscription successfully deleted'

啟用使用者互動

使用者設定檔

擷取使用者的個人資料

如要手動擷取使用者的 YouTube 個人資料,請使用下列 URI:

http://gdata.youtube.com/feeds/api/users/username

您可以使用 YouTubeService 物件的 GetYouTubeUserEntry 方法擷取 gdata.youtube.YouTubeUserEntry

user_entry = yt_service.GetYouTubeUserEntry(username='gdpython')

# we can then write a helper function to print out the user details
def PrintUserEntry(entry):
  # print required fields where we know there will be information
  print 'URI: %s\n' % entry.id.text
  print 'Age: %s\n' % entry.age.text
  print 'Gender: %s\n' % entry.gender.text
  print 'Location: %s\n' % entry.location.text

  # check if there is information in the other fields and if so print it
  if user.first_name: 
    print 'First Name: %s\n' % user.first_name.text
  if user.last_name:
    print 'Last Name: %s\n' % user.last_name.text
  if user.relationship:
    print 'Relationship: %s\n' % user.relationship.text
  if user.description:
    print 'About me: %s\n' % user.description.text
  for link in user.link:
    if link.rel == 'related':
      print 'Website: %s\n' % link.href
  if user.company:
    print 'Company: %s\n' % user.company.text
  if user.occupation:
    print 'Occupation: %s\n' % user.occupation.text
  if user.school:
    print 'School: %s\n' % user.school.text
  if user.hobbies:
    print 'Hobbies: %s\n' % user.hobbies.text
  if user.movies:
    print 'Movies: %s\n' % user.movies.text
  if user.music:
    print 'Music: %s\n' % user.music.text
  if user.books:
    print 'Books: %s\n' % user.books.text
  if user.hometown:
    print 'Hometown: %s\n' % user.hometown.text

聯絡人

您可以從下列網址擷取特定使用者的聯絡人清單:

http://gdata.youtube.com/feeds/api/users/username/contacts

擷取使用者聯絡人

YouTubeService 物件的 GetYouTubeContactFeed 方法可用於擷取由 gdata.youtube.YouTubeContactEntry 物件組成的 gdata.youtube.YouTubeContactFeed

contact_feed = yt_service.GetYouTubeContactFeed(username='GoogleDevelopers')
for entry in contact_feed.entry:
  print entry.title.text
  # find the apprpriate category element to find out the contact type
  for category in entry.category:
    if category.scheme == 'http://gdata.youtube.com/schemas/2007/contact.cat':
      print category.term

新增聯絡人

如要在使用者聯絡人資訊提供中新增聯絡人,請使用 YouTubeService 物件的 AddContact 方法。

new_contact = yt_service.AddContact(contact_username='GoogleDevelopers')

if isinstance(new_contact, gdata.youtube.YouTubeContactEntry)
  print 'New contact added'

接受/拒絕聯絡人

如要更新聯絡人,請使用 YouTubeService 物件的 UpdateContact 方法。這種方法可以接受/拒絕聯絡人要求,並且將聯絡人分類為「好友」或「家庭」。在下列範例中,我們先接受聯絡人,然後將類別設為「家庭」:

# in this case user 'gdpython' has requested to be our contact
#so the original contact status is 'pending'
updated_contact = yt_service.UpdateContact('gdpython', 'accepted', 'Family')

if isinstance(updated_contact, gdata.youtube.YouTubeContactEntry)
  print 'New contact added'

刪除聯絡人

如要刪除聯絡人,請使用 YouTubeService 物件的 DeleteContact 方法,輸入您要刪除的聯絡人使用者名稱。

response = yt_service.DeleteContact(contact_username='gdpython')

if response is True:
  print 'Contact deleted'

返回頁首