개발자 가이드: Python

YouTube Data API를 사용하면 클라이언트 애플리케이션에서 Google Data API 피드 형식의 YouTube 콘텐츠를 검색하고 업데이트할 수 있습니다. 클라이언트 애플리케이션은 YouTube Data API 피드를 사용하여 동영상, 댓글, 응답, 재생목록, 사용자 프로필, 사용자 연락처를 가져오고 검색하고 업데이트할 뿐만 아니라 특정 기준과 일치하는 동영상을 쿼리할 수도 있습니다.

이 문서에서는 YouTube Data API의 기능에 대한 배경 지식 외에 Python 클라이언트 라이브러리를 사용하여 API와 상호작용하는 예시를 제공합니다. Python 클라이언트 라이브러리를 사용하려면 Python 2.0 이상과 요소 트리, httplib, urllib 모듈이 필요합니다. 자세한 내용은 종속 항목 모듈을 참고하세요.

Python 클라이언트 라이브러리 설정에 도움이 필요한 경우 시작 가이드를 참조하세요. Python 클라이언트 라이브러리에서 YouTube와 상호작용하는 데 사용되는 기본 프로토콜에 대해 자세히 알아보려면 개발자 가이드 프로토콜 페이지를 참조하세요.

본 도움말에 대한 정보

시청자층

이 문서는 Python 클라이언트 라이브러리를 사용하여 YouTube와 상호작용할 수 있는 클라이언트 애플리케이션을 작성하려는 프로그래머를 위해 작성되었습니다. 기본 Data 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를 사용하여 동영상을 삭제하는 방법도 설명합니다.

  • 커뮤니티 기능 사용 섹션에서는 사용자가 YouTube 동영상과 상호작용할 수 있는 API 기능을 설명합니다. 이 함수는 기존 동영상에 평가, 댓글 또는 신고를 게시하기 위한 요청을 설명합니다. API를 사용하여 동영상 댓글 목록을 가져올 수도 있습니다.

  • 동영상 저장 및 수집 섹션에서는 즐겨찾는 동영상, 동영상 재생목록, YouTube 채널 구독정보에 액세스하고 이를 만들고 업데이트하는 데 API를 사용하는 방법을 설명합니다. 동영상을 추가 및 삭제하여 동영상 재생목록과 즐겨찾기를 수정하는 방법도 알려줍니다.

  • 사용자 상호작용 사용 설정 섹션에서는 API를 사용하여 사용자 프로필을 가져오고 업데이트하는 방법을 설명합니다. 이 섹션에서는 사용자 연락처를 검색, 추가, 업데이트, 삭제하는 방법도 설명합니다.

시작하기

요구사항

클라이언트 애플리케이션은 YouTube Data API 피드를 사용하여 동영상, 댓글, 응답, 재생목록, 구독, 사용자 프로필 등을 검색 및 검색할 수 있습니다.

이 문서에서는 YouTube Data API의 기능에 대한 배경 지식 외에 Python 클라이언트 라이브러리를 사용하여 API와 상호작용하는 예시를 제공합니다. Python 클라이언트 라이브러리를 사용하려면 Python 2.2 이상과 요소 트리, httplib, urllib 모듈이 필요합니다. 자세한 내용은 종속 항목 모듈을 참고하세요.

환경 구성에 대한 자세한 내용은 시작 가이드를 참조하세요. Python 클라이언트 라이브러리에서 YouTube와 상호작용하는 데 사용되는 기본 프로토콜에 대해 자세히 알아보려면 개발자 가이드 프로토콜 페이지를 참고하세요.

아래의 샘플 코드 스니펫을 복사해 코드에 붙여넣고 필요에 맞게 수정할 수 있습니다.

YouTube Data API로 작업을 하려면 먼저 아래와 같이 gdata.youtube.service.YouTubeService 객체를 초기화해야 합니다. 아래에 나열된 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를 지정하는 데 사용됩니다. 개발자 키와 클라이언트 ID는 사용 중인 인증 스키마와는 별개로 YouTubeService 객체에 설정할 수 있습니다.

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

YouTube 개발자 키에 가입해야 합니다.

웹 애플리케이션용 AuthSub 인증

AuthSub 프록시 인증은 YouTube/Google 계정에 대해 사용자를 인증해야 하는 웹 애플리케이션에서 사용합니다. 작업자는 YouTube 사용자의 사용자 이름과 비밀번호에 액세스할 필요가 없습니다. 특별한 AuthSub 토큰만 있으면 됩니다.

사용자가 애플리케이션을 처음 방문할 때 Google 서비스에서 아직 인증되지 않았습니다. 이 경우 애플리케이션의 YouTube 계정 액세스 요청을 승인하기 위해 사용자를 Google로 안내하는 링크를 제공해야 합니다. Python 클라이언트 라이브러리는 이 URL을 생성하는 함수를 제공합니다. 아래 코드는 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 메서드로 전송된 매개변수를 확인합니다.

  • 다음 — 애플리케이션이 계정에 액세스하도록 승인한 후 YouTube가 사용자를 리디렉션해야 하는 페이지의 URL입니다.
  • 범위 - 애플리케이션이 YouTube API 피드에만 액세스함을 나타냅니다.
  • secure - 반환된 토큰이 보안 토큰이 아님을 나타냅니다.
  • session — 이 토큰을 다용도 (세션) 토큰으로 교환할 수 있음을 나타냅니다.

반환된 URL은 다음과 같습니다.

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 URL로 다시 리디렉션됩니다. URL에는 쿼리 매개변수로 일회용 토큰 값이 추가됩니다. URL은 다음과 같이 표시됩니다.

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

다음 섹션에서는 이 토큰을 업그레이드하는 방법을 보여줍니다. 아래 스니펫은 URL에서 이 토큰을 가져오는 방법 중 하나를 보여줍니다.

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가 위에서 지정되었으므로 AuthSubSessionToken 서비스를 호출하는 UpgradeToSessionToken 메서드를 사용하여 이 토큰을 AuthSub 세션 토큰으로 교환할 수 있습니다.

이제 YouTubeService 객체가 완전히 인증되어 YouTube API로 추가 요청을 처리하는 데 사용할 수 있습니다. AuthSub 세션 토큰은 특별히 취소 요청을 하지 않거나 사용자가 YouTube 계정의 승인된 사이트 페이지를 방문하여 액세스 권한을 취소하기로 결정하지 않는 한 만료되지 않습니다.

설치된 애플리케이션의 ClientLogin 인증

ClientLogin 인증은 설치된 애플리케이션에서 사용되며 사용자의 사용자 이름과 비밀번호를 저장하거나 쿼리할 수 있습니다. 이 인증 형식을 사용하려면 클라이언트에서 인증 요청을 보내는 사용자의 ID와 비밀번호를 지정하여 gdata.service.GDataService 클래스에서 상속된 YouTubeServiceProgrammaticLogin 메서드를 호출합니다.

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는 표준 피드, 업로드, 구독 및 즐겨찾기와 같은 동영상 목록을 나타내는 여러 동영상 피드를 제공합니다. 각 피드의 URL은 참조 가이드에 나와 있습니다.

동영상 피드 표시

YouTube API의 많은 피드는 동영상 항목으로 구성됩니다. 이러한 피드는 대부분 여러 개의 gdata.youtube.YouTubeVideoEntry 객체를 포함하는 gdata.youtube.YouTubeVideoFeed 객체로 모델링할 수 있습니다. 각 동영상 항목은 YouTube에 있는 정확히 하나의 동영상에 해당하며 동영상에 대한 정보를 포함합니다.

동영상 목록을 가져오는 기본 구조는 동영상 피드에 대한 URL을 구성한 후 다음 코드와 비슷하게 한 번에 하나씩 항목을 처리하는 것입니다.

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

동영상 검색 및 검색 섹션에서는 여러 일반적인 피드 URL과 다양한 동영상 피드를 검색하는 방법을 자세히 설명합니다.

특정 동영상 항목 가져오기

동영상 ID를 알고 있는 경우 특정 동영상 항목에 대한 정보만 가져올 수 있습니다. 항목 URL은 동영상 ID를 기반으로 합니다.

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

다음 코드는 YouTube 동영상에 해당하는 gdata.youtube.YouTubeVideoEntry를 검색합니다.

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

동영상 항목 콘텐츠

썸네일 이미지, 플레이어 URL, 동영상 길이 등 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에서 가장 인기 있는 동영상의 피드 URL 형식은 다음과 같습니다.

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

참고: localeID를 http://gdata.youtube.com/feeds/api/standardfeeds/localeID/feedID 형식으로 지정하여 언어별 표준 피드를 검색할 수도 있습니다. 예를 들어 일본에서 가장 인기 있는 동영상은 http://gdata.youtube.com/feeds/api/standardfeeds/JP/most_popular입니다. 예상되는 localeID의 전체 목록은 참조 가이드를 확인하세요.

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))

참고: username 대신 'default' 문자열을 사용하여 현재 인증된 사용자의 동영상을 검색할 수도 있습니다.

관련 동영상을 가져오려면 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와 같은 서브클래스는 피드 URL을 구성합니다. 위에 표시된 VideoQuery는 다음과 동일한 URL을 구성합니다.

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

다음은 검색 매개변수 설정을 위한 가장 일반적인 YouTubeVideoQuery 속성입니다.

author
항목의 작성자를 설정합니다. 저자는 YouTube 사용자 이름과 동의어입니다.
format
동영상 형식을 지정합니다. 숫자 매개변수를 받아 모바일 동영상 재생을 위한 두 가지 RTSP 스트리밍 URL 또는 내장형 플래시 플레이어에 대한 HTTP URL 중 하나를 지정합니다.
racy
제한된 콘텐츠가 결과에 포함되어야 하는지를 나타냅니다. '포함' 또는 '제외'의 두 매개변수만 허용됩니다.
max_results
한 번에 반환할 최대 항목 수를 설정합니다.
start_index
페이징을 위해 가져올 첫 번째 결과의 1부터 시작하는 색인을 설정합니다.
orderby
항목을 나열할 순서를 relevance, viewCount, published, rating로 설정합니다.
time
표준 피드 결과를 today, this_week, this_month 또는 all_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 검색 요청을 보냅니다. 동영상이 일치해야 하는 카테고리 스키마와 개발자 태그를 지정해야 합니다. 아래 URL에서 개발자 태그(이 예에서는 '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))

동영상 업로드하기

업로드 프로세스에 대한 간략한 개요는 프로토콜 가이드의 다이어그램을 검토하세요. 다음 두 가지 방법 중 하나로 동영상을 업로드할 수 있습니다.

  • 직접 업로드 방법을 통해 서버에서 직접 동영상을 업로드하는 방법
  • 또는 메타데이터를 먼저 전송한 다음 사용자가 브라우저 기반 업로드 방법을 통해 YouTube에 동영상을 직접 업로드하도록 합니다.

직접 업로드

동영상을 업로드하려면 먼저 새 gdata.youtube.YouTubeVideoEntry 객체를 구성하여 필수 메타데이터를 포함하는 gdata.media.Group 객체에 전달해야 합니다. 다음 예는 Quicktime 동영상 'mytestmovie.mov'를 다음 속성과 함께 YouTube에 업로드하는 방법을 보여줍니다.

속성
Title내 테스트 영화
카테고리자동차
키워드재미있는 자동차
설명내 설명
파일 이름mytestmovie.mov
파일 MIME 유형video/quicktime
비공개 동영상 여부false
동영상 위치37,-122 (위도,경도)
개발자 태그mydevelopertag, 다른 개발자 태그

아래 코드는 업로드할 빈 YouTubeVideoEntry를 만듭니다. InsertVideoEntry 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 양식을 구성하는 데 사용되는 링크와 토큰을 출력합니다. 다음은 간단한 토큰의 예입니다. 위의 YouTubeVideoEntry에서 가져온 것처럼 반환된 토큰 요소의 콘텐츠를 나타내는 youtube_token가 있습니다. 양식을 제출한 후 사용자가 웹사이트로 리디렉션되도록 하려면 post_urlnext 매개변수를 추가해야 합니다(아래 참고). AuthSub 링크의 next 매개변수와 같은 방식으로 작동합니다. 유일한 차이점은 여기서는 일회용 토큰 대신 statusid 변수가 URL 매개변수로 반환된다는 점입니다.

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 사용자는 시청한 동영상을 즐겨찾기로 표시할 수 있습니다. 사용자가 선호하는 피드의 일반적인 위치는 다음 URL입니다.

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 사용자에게는 자신이 만든 모든 재생목록이 포함된 재생목록 피드가 있습니다. 그러면 각 재생목록에 해당 재생목록에 있는 모든 동영상에 대한 피드가 있습니다.

사용자 재생목록 검색

사용자의 모든 재생목록 목록을 직접 가져오려면 다음 URL을 사용합니다.

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')

참고: 특정 사용자 이름 (예: 위의 예의 'gdpython')을 전달하는 대신 'default' 문자열을 전달하여 현재 인증된 사용자를 참조할 수도 있습니다.

gdata.youtube.YouTubePlaylistFeedgdata.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 메서드를 사용하면 됩니다. 이 메서드는 다음 매개변수를 취합니다. 재생목록_제목, 재생목록_설명(두 문자열 모두) 및 재생목록을 비공개로 표시할 경우 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 메서드를 사용하세요. 이 메서드는 업데이트할 재생목록의 ID, 새로운 제목, 새로운 설명, 재생목록을 비공개로 설정하는 불리언(선택사항), 재생목록을 소유한 사용자 이름을 나타내는 문자열(선택사항) 등의 매개변수를 사용합니다. 문자열은 현재 인증된 사용자로 기본 설정됩니다.

# 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 사용)과 같은 코드는 인증된 사용자를 'GoogleDevelopers' 채널로 구독합니다.

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

연락처

지정된 사용자의 연락처 목록은 다음 URL에서 검색할 수 있습니다.

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'

맨 위로