= AWS/LambdaExamples = * 2021 - Coursera course * Bash script to upload python lambda in zip file {{{ #!highlight bash import boto3 import subprocess client = boto3.client('lambda') ROLE = 'arn:' + subprocess.getoutput('aws iam list-roles | grep role/lab4 | cut -f3- -d : | cut --complement -c 44,45') BUCKET = subprocess.getoutput('aws s3api list-buckets --query "Buckets[].Name" | grep s3bucket | tr -d "," | xargs') response = client.create_function( FunctionName='get_reviews', Runtime='python3.8', Role=ROLE, Handler='get_reviews_code.lambda_handler', Code={ 'S3Bucket': BUCKET, 'S3Key': 'get_reviews.zip' } ) print ("DONE") }}} * Python lambda example from course * APIGW setup, Integration mapping template, Content-Type application/json {{{ { "product_id_str": "$input.params().querystring.get('product_id')" } }}} * Test ApiGW Method Execution, "Query Strings {get_reviews}" {{{ product_id=TESTID }}} * API GW Integration response Header Mappings ||Response header || Mapping value || ||Access-Control-Allow-Headers || 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token' || ||Access-Control-Allow-Methods || 'GET' || ||Access-Control-Allow-Origin || '*' || * Python lambda code {{{ #!highlight python import boto3 import json import re def lambda_handler(event, context): product_id_str = event['product_id_str'] S3_BUCKET = 'aws-tc-largeobjects' S3_FILE = 'DEV-AWS-MO-Building_2.0/my_json_lines.jsonl' s3 = boto3.client('s3') r = s3.select_object_content( Bucket=S3_BUCKET, Key=S3_FILE, ExpressionType='SQL', Expression="select s.review_headline, s.review_body, s.star_rating from s3object[*] s where s.product_id = '" + product_id_str + "'", InputSerialization={'JSON': {"Type": "Lines"}}, OutputSerialization={'JSON': {}} ) all_reviews_list = [] helper_format_str = "" for event in r['Payload']: if 'Records' in event: helper_format_str = event['Records']['Payload'].decode('utf-8') helper_format_str = helper_format_str.replace("review_headline", "review_headline_str").replace("review_body", "review_body_str") all_reviews_list = helper_format_str.splitlines() result_list = [] for review_chunk in all_reviews_list: result_list.append(json.loads(review_chunk)) return { "product_id_str" : product_id_str, "reviews_arr": result_list } }}} * lambda python, checking and extracting info from Bearer token {{{ #!highlight python import json import base64 def lambda_handler(event, context): token_str = "" ipv4_str = "" decoded = {} return_me = {} name_str = "" extract_str = "" cell_str = "" return_me["message_str"] = "Report processing, check your phone shortly" if "Authorization" in json.dumps(event): #i.e we are at the website and have a valid Bearer token passed token_str = event["params"]["header"]["Authorization"] extract_str = token_str.replace("Bearer ", "").strip().split(".")[1] extract_str += '=' * (-len(extract_str) % 4) decoded = json.loads(base64.b64decode(extract_str)) cell_str = decoded["phone_number"] name_str = decoded["cognito:username"] ipv4_str = event["params"]["header"]["X-Forwarded-For"] return_me["cell_str"] = cell_str return_me["name_str"] = name_str return_me["name_str"] = decoded["cognito:username"] return_me["ipv4_str"] = ipv4_str return_me["message_str"] = "Report Processing" return return_me }}}