youtube API V3搜索Python

时间:2014-04-02 17:16:04

标签: python youtube-api flask

我正在尝试使用youtube-api V3 search。我有一个烧瓶Web应用程序,我正在尝试将结果输出到网页上的行中。

我从Google developers pages开始(在终端中完美运行)然后找到了this great sounding example,它会从结果中输出缩略图和超链接。然而,它在谷歌应用程序引擎上运行,我正在尝试创建一个Flask应用程序。

因此,凭借我非常有限的知识,我试图将它们合并以满足我的需求。

#!/usr/bin/python

from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
import sys
import os
import urllib

# Set API_KEY to the "API key" value from the "Access" tab of the
# Google APIs Console http://code.google.com/apis/console#access
# Please ensure that you have enabled the YouTube Data API and Freebase API
# for your project.
API_KEY = "REPLACE ME" #Yes I did replace this with my API KEY
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
QUERY_TERM = "dog"

def search_by_keyword():
    youtube = build(
      YOUTUBE_API_SERVICE_NAME, 
      YOUTUBE_API_VERSION, 
      developerKey=API_KEY
    )
    search_response = youtube.search().list(
      q=QUERY_TERM,
      part="id,snippet",
      maxResults=25
    ).execute()

    videos = []

    for search_result in search_response.get("items", []):
    if search_result["id"]["kind"] == "youtube#video":
            videos.append("%s (%s)" % (search_result["snippet"]["title"],
                                       search_result["id"]["videoId"]))

print "Videos:\n", "\n".join(videos), "\n"

if __name__ == "__main__":
  try:
    youtube_search()
  except HttpError, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)

我真正希望它做的是将结果返回到我的网页,而不仅仅是打印,但认为最好一步一步。如果我可以在终端上工作,我可以在网页上对其进行排序,但不像我想的那么简单。

目前我收到错误;

Traceback (most recent call last):
  File "search.py", line 38, in <module>
    print "Videos:\n", "\n".join(videos), "\n"
NameError: name 'videos' is not defined

这是我的第一个主要障碍,因为我期待它能够像我从两个例子中所做的那样工作。

我的第二个问题是如何将结果转换(假设我可以在上面修改)到网页上的表格中?

我打算

@app.route('/search')

包含上述代码然后;

return render_template ('search.html')

但不确定如何将结果传回到它上面,我还需要打印这个或者是我应该使用的另一个术语吗?我希望能够使用从每个返回的VideoID来对缩略图和链接进行排序。

1 个答案:

答案 0 :(得分:1)

您的视频列表是一个本地变量,并且不存在于您的功能之外&#34; search_by_keyword()&#34;要访问视频变量,您可以像这样返回该变量:

def search_by_keyword():
youtube = build(
  YOUTUBE_API_SERVICE_NAME, 
  YOUTUBE_API_VERSION, 
  developerKey=API_KEY
)
search_response = youtube.search().list(
  q=QUERY_TERM,
  part="id,snippet",
  maxResults=25
).execute()

videos = []

for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
        videos.append("%s (%s)" % (search_result["snippet"]["title"],
                                   search_result["id"]["videoId"]))
return videos

在您的主要功能中,您可以使用以下内容:

videos = search_by_keyword()

通过这种方式,您可以将视频打印到控制台或使用Flask将其发送到模板。