Turn on the YouTube Data API.
https://console.developers.google.com/project
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
Extracted from Django's 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)
Recommended Posts