Google API Python Clientを使ってYouTube Data APIv3をいじる

  • 10
    いいね
  • 0
    コメント
この記事は最終更新日から1年以上が経過しています。

アプリ登録

YouTube Data APIをonにする。

https://console.developers.google.com/project

google-api-python-clientのインストール

pip install --upgrade google-api-python-client

https://github.com/google/google-api-python-client

doc

https://developers.google.com/youtube/v3/docs/channels/list

公式サンプルコード 

sample: https://developers.google.com/youtube/v3/code_samples/python?hl=ja

完成コード

Djangoのviews.pyから抜き出し

from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse


from oauth2client.client import OAuth2WebServerFlow
import httplib2
from apiclient.discovery import build

CLIENT_ID = 'xxxxx'
CLIENT_SECRET = 'xxxxx'
FLOW = OAuth2WebServerFlow(
    client_id=CLIENT_ID,
    client_secret=CLIENT_SECRET,
    scope='https://www.googleapis.com/auth/youtube',
    redirect_uri='http://localhost:8000/account/fetch_channel/on_auth/'
)


def index_view(request):
    return render(request, 'index.html', {})


def fetch_channel(request):
    auth_uri = FLOW.step1_get_authorize_url()
    return HttpResponseRedirect(auth_uri)


def fetch_channel_on_auth(request):
    code = request.GET.get('code', None)
    credentials = FLOW.step2_exchange(code)
    http = httplib2.Http()
    http = credentials.authorize(http)
    service = build('youtube', 'v3', http=http)
    r = service.channels().list(
        mine=True,
        part="snippet"
    ).execute()
    username = r['items'][0]['snippet']['title']
    return HttpResponse(username)