From 8f4d00ebcbd6e00307694d7493a33eff223b58e8 Mon Sep 17 00:00:00 2001 From: Luke Hannan Date: Mon, 18 Mar 2024 20:57:53 +0200 Subject: [PATCH] Update single get function to be more robust --- moviedb-single.py | 54 ++++++++++++++++++++++++++++++++++------------- 1 file changed, 39 insertions(+), 15 deletions(-) mode change 100644 => 100755 moviedb-single.py diff --git a/moviedb-single.py b/moviedb-single.py old mode 100644 new mode 100755 index 2ff8d50..856b39e --- a/moviedb-single.py +++ b/moviedb-single.py @@ -1,23 +1,47 @@ import json import boto3 +from botocore.vendored import requests +import os from boto3.dynamodb.conditions import Key, Attr -# always start with the lambda_handler - +# always start with the lambda_handler def lambda_handler(event, context): + OMDB = os.environ["OMDBkey"] + # make the connection to dynamodb - # may require parameters if not using default AWS environment vars - dynamodb = boto3.resource('dynamodb') - - table = dynamodb.Table('movies') - # get item from database - items = table.get_item( - Key={"title": event["queryStringParameters"]["title"], "year": event["queryStringParameters"]["year"]}) - items = items['Item'] - - return { - 'statusCode': 200, - 'body': json.dumps(items) - } + dynamodb = boto3.resource( + "dynamodb" + ) # may require parameters if not using default AWS environment vars + + table = dynamodb.Table("movies") + + movie = requests.get( + "https://www.omdbapi.com/?apikey=" + + OMDB + + "&t=" + + event["queryStringParameters"]["title"] + + "&y=" + + event["queryStringParameters"]["year"] + ) + + if movie.json()["Response"] == "True": + + # get item from database + items = table.get_item( + Key={"title": movie.json()["Title"], "year": movie.json()["Year"]} + ) + return {"statusCode": 200, "body": json.dumps(items["Item"])} + elif ( + movie.json()["Response"] == "False" + and movie.json()["Error"] == "Daily request limit reached!" + ): + return {"statusCode": 429, "body": "OMDB API request limit reached!"} + elif ( + movie.json()["Response"] == "False" + and movie.json()["Error"] == "Movie not found!" + ): + return {"statusCode": 404, "body": "Movie Not Found!"} + else: + return {"statusCode": 520, "body": "Unknown Error!"}