如何在Django中使用youtube API搜索和显示视频

时间:2018-12-27 16:58:35

标签: python django-rest-framework

我需要使用django中的YouTube API搜索和显示视频。例如,如果我在HTML页面中搜索“猫”,它将显示YouTube中基于猫的视频的列表。

但是我得到的错误是:

  

AttributeError,位于/ youtubeapp / search / 18 / item /

     

“名称空间”对象没有属性“ META”。

我不知道该如何解决。

这是我的代码:

Views.py

from django.shortcuts import render
from django.views.generic import CreateView,TemplateView
from youtubeapp.forms import SearchForm
from youtubeapp.models import Search
import oauth2client
from oauth2client import tools

import argparse

from googleapiclient.discovery import build
from googleapiclient.errors import HttpError      


DEVELOPER_KEY = 'AIzaSyBhtNyTQMsYbFdIC1Qc1hbQG0LIT8jlAG4'
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'

def youtube_search(request):
    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,developerKey=DEVELOPER_KEY)

  # Call the search.list method to retrieve results matching the specified
  # query term.
    search_response = youtube.search().list(
        q=request.q,
        part='id,snippet',
        maxResults=request.max
    ).execute()

    videos = []
    for search_result in search_response.get('items', []):
        if search_result['id']['kind'] == 'youtube#video':
            videos.append('%s' % (search_result['snippet']['title']))
            ctx1 = ('\n'.join(videos))
            videos.append('%s' % (search_result['id']['videoId']))
            ctx2 = ('\n'.join(videos))
            mydict = {'title':ctx1,'videoid':ctx2} # I am getting the error in this line...

    return render(request,'youtubeapp/main.html',context = mydict)  

if __name__ == '__main__':
def main(request,pk):
  parser = tools.argparser
  mxRes = 3
  parser.add_argument('--q', help='Search term', default='Srce Cde')
  parser.add_argument('--max', help='Max results')
  parser.add_argument("--key", help="Required API key")

  args = parser.parse_args([])

  if not args.max:
      args.max = mxRes

  try:
    youtube_search(args) # I am getting the error in this line
  except HttpError as e:
   print('An HTTP error %d occurred:\n%s' % (e.resp.status, e.content))       

**urls.py** 

from django.conf.urls import url
from youtubeapp import views

urlpatterns=[
    url(r'^search/new/$',views.SearchCreateView.as_view(),name='search_new'),
    url(r'^search/(?P<pk>\d+)/item/$',views.main,name='main'),

]   

main.html

这将显示搜索到的视频:

{% extends 'youtubeapp/base.html' %}
{% block content %}

<div class="item">
    <h2>{{title}}</h2>
    <div class="video w100" width="640" height="360" src="//www.youtube.com/embed/{{videoid}}"></div>
</div>

{% endblock %}  

0 个答案:

没有答案