Skip to content

Instantly share code, notes, and snippets.

@m0sk1t
Created April 5, 2019 21:28
Show Gist options
  • Save m0sk1t/b97faa43909a937e2b54cbd59d01bac4 to your computer and use it in GitHub Desktop.
Save m0sk1t/b97faa43909a937e2b54cbd59d01bac4 to your computer and use it in GitHub Desktop.
Fetcher
#!/bin/python3
import sys
import os
from urllib.request import Request
from urllib.request import urlopen
from urllib.error import URLError
import json
# Complete the function below.
''' Response:
page: The current page.
per_page: The maximum number of results per page.
total: The total number of movies in the search result.
total_pages: The total number of pages which must be queried to get all the results.
data: An array of JSON objects containing movie information where the Title field denotes the title of the movie.
'''
BASE_URL = 'https://jsonmock.hackerrank.com/api/movies/search/?Title=%s&page=%s'
def get_page(substr, current_page):
req = Request(BASE_URL % (substr, current_page))
response = urlopen(req)
raw_data = response.read()
parsed_json = json.loads(raw_data.decode('utf-8'))
return parsed_json
def pages(substr):
page_number = 1
first_page = get_page(substr, page_number)
yield first_page
total_pages = first_page["total_pages"]
while page_number < total_pages:
page_number += 1
next_page = get_page(substr, page_number)
yield next_page
def getMovieTitles(substr):
MOVIE_TITLES = []
for page in pages(substr):
MOVIE_TITLES += [m['Title'] for m in page["data"]]
return sorted(MOVIE_TITLES)
f = open(os.environ['OUTPUT_PATH'], 'w')
try:
_substr = str(input())
except:
_substr = None
res = getMovieTitles(_substr)
for res_cur in res:
f.write( str(res_cur) + "\n" )
f.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment