How to use omdb method in Lemoncheesecake

Best Python code snippet using lemoncheesecake

metadata_provider_omdb.py

Source:metadata_provider_omdb.py Github

copy

Full Screen

1"""2 Copyright (C) 2016 Quinn D Granfor <spootdev@gmail.com>3 This program is free software; you can redistribute it and/or4 modify it under the terms of the GNU General Public License5 version 2, as published by the Free Software Foundation.6 This program is distributed in the hope that it will be useful, but7 WITHOUT ANY WARRANTY; without even the implied warranty of8 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU9 General Public License version 2 for more details.10 You should have received a copy of the GNU General Public License11 version 2 along with this program; if not, write to the Free12 Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,13 MA 02110-1301, USA.14"""15import inspect16import omdb17from common import common_logging_elasticsearch_httpx18class CommonMetadataOMDB:19 """20 Class for interfacing with omdb21 """22 def __init__(self):23 pass24 async def com_omdb_get(self, media_title, media_year, media_fullplot, media_tomatoes):25 await common_logging_elasticsearch_httpx.com_es_httpx_post_async(message_type='info',26 message_text={27 'function':28 inspect.stack()[0][29 3],30 'locals': locals(),31 'caller':32 inspect.stack()[1][33 3]})34 omdb.get(title=media_title, year=media_year, fullplot=media_fullplot,35 tomatoes=media_tomatoes)36 async def com_omdb_search(self, media_title):37 """38 Search39 """40 await common_logging_elasticsearch_httpx.com_es_httpx_post_async(message_type='info',41 message_text={42 'function':43 inspect.stack()[0][44 3],45 'locals': locals(),46 'caller':47 inspect.stack()[1][48 3]})49 omdb.search(media_title)50 async def com_omdb_search_movie(self, media_title):51 """52 Search movie53 """54 await common_logging_elasticsearch_httpx.com_es_httpx_post_async(message_type='info',55 message_text={56 'function':57 inspect.stack()[0][58 3],59 'locals': locals(),60 'caller':61 inspect.stack()[1][62 3]})63 omdb.search_movie(media_title)64 async def com_omdb_search_episode(self, media_title):65 """66 Search episode67 """68 await common_logging_elasticsearch_httpx.com_es_httpx_post_async(message_type='info',69 message_text={70 'function':71 inspect.stack()[0][72 3],73 'locals': locals(),74 'caller':75 inspect.stack()[1][76 3]})77 omdb.search_episode(media_title)78 async def com_omdb_search_series(self, media_title):79 """80 Search series81 """82 await common_logging_elasticsearch_httpx.com_es_httpx_post_async(message_type='info',83 message_text={84 'function':85 inspect.stack()[0][86 3],87 'locals': locals(),88 'caller':89 inspect.stack()[1][90 3]})91 omdb.search_series(media_title)92 async def com_omdb_imdb(self, imdbid):93 """94 Info by IMDB id95 """96 await common_logging_elasticsearch_httpx.com_es_httpx_post_async(message_type='info',97 message_text={98 'function':99 inspect.stack()[0][100 3],101 'locals': locals(),102 'caller':103 inspect.stack()[1][104 3]})105 omdb.imdbid(imdbid)106 async def com_omdb_title(self, media_title):107 """108 Grab by title109 """110 await common_logging_elasticsearch_httpx.com_es_httpx_post_async(message_type='info',111 message_text={112 'function':113 inspect.stack()[0][114 3],115 'locals': locals(),116 'caller':117 inspect.stack()[1][118 3]})119 omdb.title(media_title)120 async def com_omdb_default(self):121 """122 Set defaults for data returned123 """124 await common_logging_elasticsearch_httpx.com_es_httpx_post_async(message_type='info',125 message_text={126 'function':127 inspect.stack()[0][128 3],129 'locals': locals(),130 'caller':131 inspect.stack()[1][132 3]})133 omdb.set_default('tomatoes', True)134 async def com_omdb_request(self, media_title, media_year, media_fullplot, media_tomatoes):135 await common_logging_elasticsearch_httpx.com_es_httpx_post_async(message_type='info',136 message_text={137 'function':138 inspect.stack()[0][139 3],140 'locals': locals(),141 'caller':142 inspect.stack()[1][143 3]})...

Full Screen

Full Screen

movie_app.py

Source:movie_app.py Github

copy

Full Screen

1from flask import Flask, render_template, request2import json3import sys4import urllib5from urllib.parse import urlencode6from urllib.request import urlopen7app = Flask(__name__)8class OMDBError(Exception):9 """10 OMDBError represents an error returned by the OMDB API.11 """12 pass13class Movie(object):14 """15 Movie objects contain all OMDB information about a particular movie,16 including the title and rating.17 """18 def __init__(self, raw_data):19 # Store the raw data from OMDB in this object so that we can use the20 # data in the getter functions.21 self.omdb_data = raw_data22 def get_movie_title(self):23 """24 get_movie_title is a getter function that returns the movie title.25 """26 # Return the title key from the OMDB data.27 return self.omdb_data["Title"]28 def get_movie_rating(self, source="Rotten Tomatoes"):29 """30 get_movie_rating is a getter function that returns the Rotten Tomatoes rating.31 """32 # There can be multiple ratings for each movie, so they are stored as a33 # list of ratings, each with a source and a rating. By default, we are34 # only interested in Rotten Tomatoes ratings, so we loop through each35 # rating and return it if the source is Rotten Tomatoes.36 for ratings in self.omdb_data["Ratings"]:37 if ratings["Source"] == source:38 return ratings["Value"]39 # If no matching rating is found, we will raise an error.40 raise Exception("Rating for source {0} was not found!".format(source))41class OMDB(object):42 """43 OMDB objects represent clients to the OMDB API. It has helper methods for44 performing functions on the API.45 """46 def __init__(self, apikey):47 # Store the API key so it may be used later to build the authenticated URL.48 self.apikey = apikey49 def build_url(self, **kwargs):50 """51 build_url returns a properly formatted URL to the OMDB API including the52 API key.53 """54 # Add api key to dictionary of parameters to send to OMDB.55 kwargs["apikey"] = self.apikey56 # Start building URL.57 url = "http://www.omdbapi.com/?"58 # urlencode the API parameters dictionary and append it to the url.59 url += urlencode(kwargs)60 # Return the complete URL.61 return url62 def call_api(self, **kwargs):63 """64 call_api uses the provided parameters to create a URL to the OMDB API,65 call the API, parse the results, and return the parsed JSON data.66 If the API returns an error, the error is raised as an exception.67 """68 # Given the parameters (kwargs), build a URL.69 url = self.build_url(**kwargs)70 # Call the API by opening the url and reading the data.71 response = urlopen(url)72 response_data = response.read()73 # Decode the raw JSON data74 response_data_decoded = json.loads(response_data)75 # Check for an error and throw an exception if needed76 if "Error" in response_data_decoded:77 raise OMDBError(response_data_decoded["Error"])78 # Return the decoded data79 return response_data_decoded80 def get_movie_by_title(self, query):81 """82 Get a movie object containing all the data for a single movie. Returns83 a single movie object.84 """85 # Call the API, passing the query as "t" (by title).86 data = self.call_api(t=query)87 # Create a Movie with the raw results from the API call.88 return Movie(data)89 def get_movie_by_id(self, id):90 """91 Get a movie object containing all the data for a single movie. Returns92 a single movie object.93 """94 # Call the API, passing the query as "i" (by id).95 data = self.call_api(i=id)96 # Create a Movie with the raw results from the API call.97 return Movie(data)98 def search(self, query):99 """100 Search for movies based on keywords. Returns list of dictionaries.101 """102 # Call the API, passing the query as "s" (by search).103 data = self.call_api(s=query)104 # Return the list of movie dictionaries.105 return data["Search"]106def get_apikey():107 """108 Read API key from file on disk.109 """110 # Open file in read mode (r).111 with open("omdb-api-key.txt", "r") as file:112 # Read the file into a variable (key).113 key = file.read()114 # Strip any whitespace characters such as a newline that may be present115 # in the file.116 key = key.strip()117 # Return the key118 return key119def list_search_results(movie_to_look_up):120 """121 Prompt for search term and print list of matching movies.122 """123 # Read the API key from disk.124 apikey = get_apikey()125 # Create OMDB client with provided API key.126 omdb = OMDB(apikey)127 # Ask user for search term.128 query = input("Enter a search term: ")129 # Get results from OMDB API. If OMDB error occurs, print the error message and exit.130 try:131 matching_movie_list = omdb.search(movie_to_look_up)132 except OMDBError as err:133 print("OMDB Error: {0}".format(err))134 return135 # Extract titles from search result list with list comprehension (each136 # result is a dictionary).137 movie_titles = [each_movie["Title"] for each_movie in matching_movie_list]138 # Loop through list of titles and print them (indented with 4 spaces).139 for title in movie_titles:140 print(" " + title)141def return_single_movie_object(movie_to_look_up):142 """143 Prompt for movie title and print Rotten Tomatoes rating.144 """145 # Read the API key from disk.146 apikey = get_apikey()147 # Create OMDB client with provided API key.148 omdb = OMDB(apikey)149 # Ask user for movie title.150 query = input("Enter the movie title: ")151 # Get Movie object. If OMDB error occurs, print the error message and exit.152 try:153 my_movie_object = omdb.get_movie(movie_to_look_up)154 return my_movie_object155 except OMDBError as err:156 print("OMDB Error: {0}".format(err))157 return158def print_single_movie_rating(movie_query):159 my_movie = return_single_movie_object(movie_query)160 # Print the rating. Note that we have to escape the quotes around the movie161 # title because those quotes are inside a string that also uses quotes.162 print("The rating for \"{0}\" is {1}.".format(my_movie.get_movie_title(), my_movie.get_movie_rating()))163def print_all_ratings(movie_list):164 for movie in movie_list:165 movie_object = return_single_movie_object(movie)166 print("The movie", movie_object.get_movie_title(), "has a rating of", movie_object.get_movie_rating())167def cli_app():168 """169 cli_app is the entrypoint into the program, and it calls into the search or170 ratings functions depending on what the user decides to do.171 """172 # We set up an infinite loop (while True) so that we can keep asking the173 # user the same question until they give us valid input ("1" or "2"). As174 # soon as a valid input is reached, the appropriate function runs and the175 # loop is terminated with "break".176 while True:177 # Enter search or ratings function.178 search_or_ratings = input("Search (1) or Ratings (2)? ")179 # Check if input was "1" or "2" and dispatch to correct functions if so.180 if search_or_ratings == "1":181 search()182 break183 elif search_or_ratings == "2":184 ratings()185 break186 # If input is not valid (any value other than "1" or "2"), notify user and next loop will ask them the question again.187 else:188 print("Error: Input must be 1 or 2!")189@app.route("/", methods=["GET"])190def home():191 # Read the API key from disk.192 apikey = get_apikey()193 # Create OMDB client with provided API key.194 omdb = OMDB(apikey)195 # Get the search query from the form.196 query = request.args.get("query", "")197 print("QUERY IS", query)198 # If a query is present, get search results from OMDB and render template.199 if query:200 results = omdb.search(query)201 return render_template("home.html", query=query, results=results)202 # If no query is present, render page without query/results203 return render_template("home.html")204@app.route("/movies/<id>", methods=["GET"])205def movie(id):206 # Read the API key from disk.207 apikey = get_apikey()208 # Create OMDB client with provided API key.209 omdb = OMDB(apikey)210 # Get the movie from OMDB and gather needed data for template.211 # Ideally we would catch any exceptions in the following and return an212 # appropriate error page. For now it will just throw a regular HTTP 500 if213 # any errors occur.214 movie = omdb.get_movie_by_id(id)215 title = movie.omdb_data["Title"]216 year = movie.omdb_data["Year"]217 poster = movie.omdb_data["Poster"]218 plot = movie.omdb_data["Plot"]219 # movie.get_rating() often errors due to no rating present, so we will220 # catch this error specifically.221 try:222 rating = movie.get_movie_rating()223 except OMDBError:224 rating = "(unavailable)"225 # Render template with all needed variables.226 return render_template("movie.html", title=title, year=year, poster=poster, plot=plot, rating=rating)227def flask_app():228 app.run(debug=True)229if __name__ == "__main__":230 # Check command line argument for "flask" and run Flask app if so.231 if len(sys.argv) > 1 and sys.argv[1] == "flask":232 flask_app()233 else:234 print('Run "./main.py flask" for the Flask app.')...

Full Screen

Full Screen

test_omdb_movie_client.py

Source:test_omdb_movie_client.py Github

copy

Full Screen

1import unittest2from datetime import date3from unittest.mock import patch, call, Mock4import requests5from requests import Timeout6from flaskr.model.response import Response7from flaskr.omdb_movie_client import OmdbMovieClient, Movie8from tests.application_test import application_test9from tests.configuration.configuration_test import TestConfiguration10from tests.fixtures.omdb_movie_response_fixture import mock_omdb_movie_response11@application_test()12class OmdbMovieClientTest(unittest.TestCase):13 @patch("flaskr.omdb_movie_client.requests.get", side_effect=mock_omdb_movie_response)14 def test_should_fetch_single_movie_response_given_single_movie_title(self,15 get_requests_mock):16 omdb_movie_client = OmdbMovieClient()17 omdb_movie_client.get_movies_response_for(titles=["3 idiots"])18 get_requests_mock.assert_called_once_with(19 f"http://www.omdbapi.com/?t=3 idiots&apikey={TestConfiguration.OMDB_API_KEY}")20 @patch("flaskr.omdb_movie_client.requests.get", side_effect=mock_omdb_movie_response)21 def test_should_fetch_multiple_movie_responses_given_multiple_movie_titles(self, get_requests_mock):22 omdb_movie_client = OmdbMovieClient()23 omdb_movie_client.get_movies_response_for(["3 idiots", "Jumanji"])24 get_requests_mock.assert_has_calls(25 [call(f"http://www.omdbapi.com/?t=3 idiots&apikey={TestConfiguration.OMDB_API_KEY}"),26 call(f"http://www.omdbapi.com/?t=Jumanji&apikey={TestConfiguration.OMDB_API_KEY}")],27 any_order=False)28 @patch("flaskr.omdb_movie_client.requests.get", side_effect=mock_omdb_movie_response)29 def test_should_return_a_movie_response_with_title_given_single_movie_title(self, get_requests_mock):30 omdb_movie_client = OmdbMovieClient()31 movie_response: Response[Movie, str] = omdb_movie_client.get_movies_response_for(["3 idiots"])32 self.assertEqual("3 idiots", movie_response.success_at(0).t().title)33 @patch("flaskr.omdb_movie_client.requests.get", side_effect=mock_omdb_movie_response)34 def test_should_return_a_movie_response_with_director_given_single_movie_title(self, get_requests_mock):35 omdb_movie_client = OmdbMovieClient()36 movie_response: Response[Movie, str] = omdb_movie_client.get_movies_response_for(["3 idiots"])37 self.assertEqual("Rajkumar Hirani", movie_response.success_at(0).t().director)38 @patch("flaskr.omdb_movie_client.requests.get", side_effect=mock_omdb_movie_response)39 def test_should_return_a_movie_response_with_release_date_given_single_movie_title(self, get_requests_mock):40 omdb_movie_client = OmdbMovieClient()41 movie_response: Response[Movie, str] = omdb_movie_client.get_movies_response_for(["3 idiots"])42 self.assertEqual(date(2009, 12, 25), movie_response.success_at(0).t().released_date)43 @patch("flaskr.omdb_movie_client.requests.get", side_effect=mock_omdb_movie_response)44 def test_should_return_a_movie_response_with_a_rating_from_internet_given_single_movie_title(self,45 get_requests_mock):46 omdb_movie_client = OmdbMovieClient()47 movie_response: Response[Movie, str] = omdb_movie_client.get_movies_response_for(["3 idiots"])48 self.assertEqual("internet", movie_response.success_at(0).t().rating_source_at(0))49 @patch("flaskr.omdb_movie_client.requests.get", side_effect=mock_omdb_movie_response)50 def test_should_return_a_movie_response_with_a_rating_of_9_on_10_given_single_movie_title(self, get_requests_mock):51 omdb_movie_client = OmdbMovieClient()52 movie_response: Response[Movie, str] = omdb_movie_client.get_movies_response_for(["3 idiots"])53 self.assertEqual("9/10", movie_response.success_at(0).t().rating_value_at(0))54 @patch("flaskr.omdb_movie_client.requests.get")55 def test_should_return_a_failure_given_request_fails_with_timeout(self, get_requests_mock):56 omdb_movie_client = OmdbMovieClient()57 get_requests_mock.side_effect = Timeout58 movie_response: Response[Movie, str] = omdb_movie_client.get_movies_response_for(["3 idiots"])59 self.assertEqual(1, movie_response.failure_count())60 @patch("flaskr.omdb_movie_client.requests.get")61 def test_should_a_failure_given_request_fails_with_internal_server_error(self, get_requests_mock):62 omdb_movie_client = OmdbMovieClient()63 def mock_response(url):64 response_mock = Mock()65 response_mock.status_code = 50066 response_mock.raise_for_status.side_effect = requests.exceptions.HTTPError67 return response_mock68 get_requests_mock.side_effect = mock_response69 movie_response: Response[Movie, str] = omdb_movie_client.get_movies_response_for(["3 idiots"])70 self.assertEqual(1, movie_response.failure_count())71 @patch("flaskr.omdb_movie_client.requests.get")72 def test_should_return_a_failure_with_movie_title_given_request_fails_Timeout(self,73 get_requests_mock):74 omdb_movie_client = OmdbMovieClient()75 get_requests_mock.side_effect = Timeout76 movie_response: Response[Movie, str] = omdb_movie_client.get_movies_response_for(["3 idiots"])...

Full Screen

Full Screen

movie_sorter.py

Source:movie_sorter.py Github

copy

Full Screen

...95 return c.ERROR 96 97 return resp.json()98#returns the omdb details of movie including the ratings99def get_movie_omdb(imdb_id):100 payload = {'i': str(imdb_id), 'apikey': c.OMDB_KEY}101 resp = requests.get(c.OMDB_URL, params = payload)102 if resp.status_code != c.OK_STATUS or not resp.json()["Response"]: #movie not found103 return c.ERROR104 105 return resp.json()106 107def get_movies_in_dir(path):108 movies_found = []109 movies_not_found = []110 for entry in os.scandir(path):111 if entry.is_dir():112 #get current movie 113 movie_year = get_name_and_year(entry.name)114 115 curr_movie = Movie(movie_year[0], int(movie_year[1]))116 #get TMDB id from TMDB117 tmdb_id = get_tmdb_id(movie_year[0], movie_year[1])118 119 if(tmdb_id != c.ERROR):120 #get movie info and imdb id from TMDB121 tmdb_json = get_movie_tmdb(tmdb_id)122 123 #get movie info from OMDB not seen in TMDB124 omdb_json = get_movie_omdb(tmdb_json["imdb_id"])125 126 if(tmdb_json != c.ERROR and omdb_json != c.ERROR):127 curr_movie.set_properties(tmdb_json, omdb_json)128 movies_found.append(curr_movie)129 else:130 movies_not_found.append(entry.name)131 else:132 movies_not_found.append(entry.name)133 ...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Lemoncheesecake automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful