11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-09-17

アプリ登録

YouTube Data APIをonにする。

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

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

doc

公式サンプルコード 

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)
11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?