تشرح نماذج أكواد Python التالية كيفية استخدام App Engine لإجراء استدعاءات YouTube Data API (الإصدار 3). يمكنك تنزيل عيّنات التعليمات البرمجية هذه من مستودعات نماذج رمز Python في Google App Engine على GitHub.
المتطلبات الأساسية
يجب إعداد مشروع في وحدة التحكم في واجهة Google API والحصول على مفتاح واجهة برمجة تطبيقات لتتمكن من تشغيل نماذج الرموز أدناه. في الوقت الحالي، يحدِّد كل مشروع متغيّر API_KEY تم ضبطه على القيمة REPLACE_ME. عليك استبدال هذه القيمة بمفتاح واجهة برمجة التطبيقات الخاص بك لتتمكّن من تشغيل النماذج.
ملاحظة مهمّة: لتشغيل كلّ هذه الأمثلة، يجب تفعيل YouTube Data API (الإصدار 3) وFreebase API للمشروع المرتبط بمفتاح واجهة برمجة التطبيقات. إذا كان تطبيقك يصل إلى بيانات القناة أو المستخدم الخاص، ستحتاج أيضًا إلى معرِّف عميل OAuth 2.0.
عيّنات تعليمات برمجية
البحث حسب الكلمة الرئيسية
يستدعي نموذج الرمز أدناه طريقة search.list لواجهة برمجة التطبيقات لاسترداد نتائج البحث المرتبطة بكلمة رئيسية معيّنة.
import os import urllib import webapp2 import jinja2 from apiclient.discovery import build from optparse import OptionParser JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape']) # Set DEVELOPER_KEY to the "API key" value from the Google Developers Console: # https://console.developers.google.com/project/_/apiui/credential # Please ensure that you have enabled the YouTube Data API for your project. DEVELOPER_KEY = "REPLACE_ME" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" class MainHandler(webapp2.RequestHandler): def get(self): if DEVELOPER_KEY == "REPLACE_ME": self.response.write("""You must set up a project and get an API key to run this project. Please visit <landing page> to do so.""" else: youtube = build( YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY) search_response = youtube.search().list( q="Hello", part="id,snippet", maxResults=5 ).execute() videos = [] channels = [] playlists = [] 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"])) elif search_result["id"]["kind"] == "youtube#channel": channels.append("%s (%s)" % (search_result["snippet"]["title"], search_result["id"]["channelId"])) elif search_result["id"]["kind"] == "youtube#playlist": playlists.append("%s (%s)" % (search_result["snippet"]["title"], search_result["id"]["playlistId"])) template_values = { 'videos': videos, 'channels': channels, 'playlists': playlists } self.response.headers['Content-type'] = 'text/plain' template = JINJA_ENVIRONMENT.get_template('index.html') self.response.write(template.render(template_values)) app = webapp2.WSGIApplication([ ('/.*', MainHandler), ], debug=True)
البحث حسب الموضوع
يستدعي نموذج الرمز أدناه طريقة search.list لواجهة برمجة التطبيقات لاسترداد نتائج البحث المرتبطة بموضوع Freebase معيّن.
import os import urllib import webapp2 import jinja2 from apiclient.discovery import build from optparse import OptionParser import json JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape']) REGISTRATION_INSTRUCTIONS = """ You must set up a project and get an API key to run this code. Please see the instructions for creating a project and a key at <a href="https://developers.google.com/youtube/registering_an_application" >https://developers.google.com/youtube/registering_an_application</a>. <br><br> Make sure that you have enabled the YouTube Data API (v3) and the Freebase API for your project.""" # Set API_KEY to the "API key" value from the Google Developers Console: # https://console.developers.google.com/project/_/apiui/credential # Please ensure that you have enabled the YouTube Data API and Freebase API # for your project. API_KEY = "REPLACE_ME" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" FREEBASE_SEARCH_URL = "https://www.googleapis.com/freebase/v1/search?%s" QUERY_TERM = "dog" class MainHandler(webapp2.RequestHandler): def get(self): if API_KEY == 'REPLACE_ME': self.response.write(REGISTRATION_INSTRUCTIONS) else: # Present a list of Freebase topic IDs for the query term self.list_topics(QUERY_TERM) def list_topics(self, QUERY_TERM): # Retrieve a list of Freebase topics associated with the query term freebase_params = dict(query=QUERY_TERM, key=API_KEY) freebase_url = FREEBASE_SEARCH_URL % urllib.urlencode(freebase_params) freebase_response = json.loads(urllib.urlopen(freebase_url).read()) if len(freebase_response["result"]) == 0: exit("No matching terms were found in Freebase.") # Create a page that shows a select box listing the topics. # When the user selects a topic and submits the form, the # 'post' method below will handle the form submission and # retrieve videos for the selected topic. select_topic_page = (''' <html> <body> <p>The following topics were found:</p> <form method="post"> <select name="topic"> ''') for result in freebase_response["result"]: select_topic_page += ('<option value="' + result["mid"] + '">' + result.