Skip to content

Commit fc5c6db

Browse files
"Added sample: python_appengine/search/main.py"
1 parent c8aacdb commit fc5c6db

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

python_appengine/search/main.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import os
2+
import urllib
3+
import webapp2
4+
import jinja2
5+
6+
from apiclient.discovery import build
7+
from optparse import OptionParser
8+
9+
JINJA_ENVIRONMENT = jinja2.Environment(
10+
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
11+
extensions=['jinja2.ext.autoescape'])
12+
13+
# Set DEVELOPER_KEY to the "API key" value from the "Access" tab of the
14+
# Google APIs Console http://code.google.com/apis/console#access
15+
# Please ensure that you have enabled the YouTube Data API for your project.
16+
DEVELOPER_KEY = "REPLACE_ME"
17+
YOUTUBE_API_SERVICE_NAME = "youtube"
18+
YOUTUBE_API_VERSION = "v3"
19+
20+
class MainHandler(webapp2.RequestHandler):
21+
22+
def get(self):
23+
if DEVELOPER_KEY == "REPLACE_ME":
24+
self.response.write("""You must set up a project and get an API key
25+
to run this project. Please visit
26+
<landing page> to do so."""
27+
else:
28+
youtube = build(
29+
YOUTUBE_API_SERVICE_NAME,
30+
YOUTUBE_API_VERSION,
31+
developerKey=DEVELOPER_KEY)
32+
search_response = youtube.search().list(
33+
q="Hello",
34+
part="id,snippet",
35+
maxResults=5
36+
).execute()
37+
38+
videos = []
39+
channels = []
40+
playlists = []
41+
42+
for search_result in search_response.get("items", []):
43+
if search_result["id"]["kind"] == "youtube#video":
44+
videos.append("%s (%s)" % (search_result["snippet"]["title"],
45+
search_result["id"]["videoId"]))
46+
elif search_result["id"]["kind"] == "youtube#channel":
47+
channels.append("%s (%s)" % (search_result["snippet"]["title"],
48+
search_result["id"]["channelId"]))
49+
elif search_result["id"]["kind"] == "youtube#playlist":
50+
playlists.append("%s (%s)" % (search_result["snippet"]["title"],
51+
search_result["id"]["playlistId"]))
52+
53+
template_values = {
54+
'videos': videos,
55+
'channels': channels,
56+
'playlists': playlists
57+
}
58+
59+
self.response.headers['Content-type'] = 'text/plain'
60+
template = JINJA_ENVIRONMENT.get_template('index.html')
61+
self.response.write(template.render(template_values))
62+
63+
app = webapp2.WSGIApplication([
64+
('/.*', MainHandler),
65+
], debug=True)

0 commit comments

Comments
 (0)