質問編集履歴
1
views.py内のsearch関数のコードを追加しました。
title
CHANGED
File without changes
|
body
CHANGED
@@ -71,4 +71,61 @@
|
|
71
71
|
```
|
72
72
|
Python 3.6.5
|
73
73
|
Django==2.1.1
|
74
|
-
```
|
74
|
+
```
|
75
|
+
|
76
|
+
###補足
|
77
|
+
`views.py`内のsearch関数はYouTubeAPIの公式(https://developers.google.com/youtube/v3/code_samples/python?hl=ja#search_by_keyword)のコードを流用しました。
|
78
|
+
|
79
|
+
search.py
|
80
|
+
```
|
81
|
+
from apiclient.discovery import build
|
82
|
+
from apiclient.errors import HttpError
|
83
|
+
from oauth2client.tools import argparser
|
84
|
+
from .youtube_data_model import YouTubeData
|
85
|
+
|
86
|
+
|
87
|
+
DEVELOPER_KEY = "MY_DEVELOPER_KEY"
|
88
|
+
YOUTUBE_API_SERVICE_NAME = "youtube"
|
89
|
+
YOUTUBE_API_VERSION = "v3"
|
90
|
+
|
91
|
+
|
92
|
+
def youtube_search(options):
|
93
|
+
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
|
94
|
+
developerKey=DEVELOPER_KEY)
|
95
|
+
|
96
|
+
saerch_response = youtube.search().list(
|
97
|
+
q=options.q,
|
98
|
+
part="id,snippet",
|
99
|
+
maxResults=options.max_results
|
100
|
+
).execute()
|
101
|
+
|
102
|
+
videos_name = []
|
103
|
+
videos_id = []
|
104
|
+
|
105
|
+
for saerch_result in saerch_response.get("items", []):
|
106
|
+
if saerch_result["id"]["kind"] == "youtube#video":
|
107
|
+
videos_name.append(saerch_result["snippet"]["title"])
|
108
|
+
videos_id.append(saerch_result["id"]["videoId"])
|
109
|
+
|
110
|
+
return videos_name, videos_id
|
111
|
+
|
112
|
+
|
113
|
+
def search(keyword):
|
114
|
+
ytdata = YouTubeData(q=keyword, max_results=10)
|
115
|
+
|
116
|
+
try:
|
117
|
+
return youtube_search(ytdata)
|
118
|
+
except HttpError as e:
|
119
|
+
print("An HTTP error %d occurrede::\n%s" % (e.resp.status, e.content))
|
120
|
+
|
121
|
+
```
|
122
|
+
youtube_data_model.py
|
123
|
+
```
|
124
|
+
class YouTubeData():
|
125
|
+
def __init__(self, q, max_results):
|
126
|
+
self.q = q
|
127
|
+
self.max_results = max_results
|
128
|
+
```
|
129
|
+
|
130
|
+
戻り値は動画タイトルと動画IDのリストです。
|
131
|
+
戻り値は`videos_name`,`videos_id`の順番で戻っており、`views.py`内においても、`videos_name`,`videos_id`は正しい値が格納されていることは確認できています。
|