(코린이는 코딩 어린이의 줄임말이다.)
가장 큰 역경은 물론 flask와 ajax 그 어디쯤에 있었다. youtube.py로 크롤링해온 정보를 app.py를 거져서 list.html로 보내 화면에 출력해야했는데 도저히 뭐가 보내지지가 않았다.
ajax로 크롤링해온 정보 받아오면 되는거야냐? 어려울게 없는데?
라고 생각했던 과거의 나.....😭😭😭 반성해라...
4주차에서 어느정도 flask에 대해서 공부를 했다고 생각했는데 아직 멀었나보다. app.py가 아닌 다른 곳에서 얻어온 정보를 app.py를 거쳐 html로 보내기까지의 과정을 아직 이해하지 못해서 그런지 youtube.py파일을 app.py에 임포트하는 순간부터 알 수 없는 에러와의 전쟁이었다. 심지어 마지막에는 RuntimeError가 발생하면서 서버마저 작동하지 않았고.. 일단 이 부분을 미뤄두기로 했다.
google youtube api 관련 코드
#!/usr/bin/python
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from oauth2client.tools import argparser
# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps
# tab of
# https://cloud.google.com/console
# Please ensure that you have enabled the YouTube Data API for your project.
DEVELOPER_KEY = ""
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
def youtube_search():
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 = q_value,
order = "date",
part = "snippet",
maxResults = 50
).execute()
print(search_response)
videos = []
channels = []
playlists = []
# Add each result to the appropriate list, and then display the lists of
# matching videos, channels, and 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"]))
print("\n\nVideos:\n\n", "\n".join(videos), "\n")
print("\n\nChannels:\n\n", "\n".join(channels), "\n")
print("\n\nPlaylists:\n\n", "\n".join(playlists), "\n")
if __name__ == "__main__":
argparser.add_argument("--q", help="Search term", default="Google")
argparser.add_argument("--max-results", help="Max results", default=25)
args = argparser.parse_args()
try:
youtube_search(args)
except HttpError as e:
print("An HTTP error %d occurred:\n%s"% (e.resp.status, e.content))
google에서 제공하는 api guide에 있는 코드에서 필요한 부분을 수정해서 사용하면 된다. DEVELOPER KEY는 구글개발자 계정을 만들면 고유 번호를 준다. 계정 당 12개의 api를 무료로 제공한다. Postman에서 key가 제대로 작동하는지 확인할 수 있다.
주의할 점은 google에서는 apiclient패키지를 받아서 import apiclient.discovery하라고 되어있지만 이대로 따라하다보면 패키지를 찾을 수 없다는 에러가 발생한다. 이 떄 apiclient가 아닌 googleapiclient 패키지를 다운받으면 문제가 해결된다. 아마 패키지는 업데이트가 되었는데 api문서는 이전 버전에 대한 설명을 하고 있는 것 같다.
참고하 포스팅
👇 영상 title출력 성공
관련 내용은 포스팅해 두었다.
관련 포스팅 클릭 (flask - 템플릿 상속)
앞으로 해결해 나가야 할 고난과 역경
메인페이지 index.html
영상출력페이지 list.html
{
videoId: '유튜브 영상 ID',
가게이름: '~~~',
locationUrl: 'https://~~~'(url),
categories: ['한식', '중식','일식','양식','분식'],
comment: '쭈꾸미튀김을 꼭 먹자'
createdAt: 지금시간
}