Skip to content

Instantly share code, notes, and snippets.

@m0sk1t
Created April 5, 2019 21:28
Show Gist options
  • Select an option

  • Save m0sk1t/b97faa43909a937e2b54cbd59d01bac4 to your computer and use it in GitHub Desktop.

Select an option

Save m0sk1t/b97faa43909a937e2b54cbd59d01bac4 to your computer and use it in GitHub Desktop.

Revisions

  1. m0sk1t created this gist Apr 5, 2019.
    57 changes: 57 additions & 0 deletions fetcher.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    #!/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()