def _query_api(self, title, year=None): name = title if year: name += ' (' + text_type(year) + ')' log.info('Querying imdb api for %s', name) api = Imdb() imdb_movies = api.search_for_title(title) # Find the first movie that matches the title (and year if present) for movie in imdb_movies: if self.sanitize_imdb_title( movie['title']) == self.sanitize_imdb_title(title): # If a year is present, it should also be the same if year: if movie['year'] == text_type(year): return movie['imdb_id'], int(movie['year']) else: continue # If no year is present, take the first match else: return movie['imdb_id'], int(movie['year']) # If no match is found, try to search for alternative titles of the first (most relevant) result if len(imdb_movies) > 0: best_match = imdb_movies[0] best_match_title_versions = api.get_title_versions( best_match['imdb_id']) if best_match_title_versions and 'alternateTitles' in best_match_title_versions: for alternate_title in best_match_title_versions[ 'alternateTitles']: if self.sanitize_imdb_title( alternate_title['title'] ) == self.sanitize_imdb_title(title): # If a year is present, it should also be the same if year: if best_match['year'] == text_type(year): return best_match['imdb_id'], int( best_match['year']) else: continue # If no year is present, take the first match else: return best_match['imdb_id'], text_type( best_match['year']) return None, year