Differences between revisions 3 and 4
Revision 3 as of 2021-07-07 10:08:34
Size: 3449
Editor: PieterSmit
Comment:
Revision 4 as of 2021-07-07 10:10:51
Size: 3542
Editor: PieterSmit
Comment:
Deletions are marked like this. Additions are marked like this.
Line 36: Line 36:
}}}
  * Test ApiGW Method Execution, "Query Strings {get_reviews}" {{{
product_id=TESTID

AWS/LambdaExamples

  • 2021 - Coursera course
  • Bash script to upload python lambda in zip file

       1 import boto3
       2 import subprocess
       3 
       4 client = boto3.client('lambda')
       5 ROLE = 'arn:' + subprocess.getoutput('aws iam list-roles | grep role/lab4 | cut -f3- -d : | cut  --complement -c 44,45')
       6 BUCKET = subprocess.getoutput('aws s3api list-buckets --query "Buckets[].Name" | grep s3bucket | tr -d "," | xargs')
       7 
       8 
       9 response = client.create_function(
      10     FunctionName='get_reviews',
      11     Runtime='python3.8',
      12     Role=ROLE,
      13     Handler='get_reviews_code.lambda_handler',
      14     Code={
      15         'S3Bucket': BUCKET,
      16         'S3Key': 'get_reviews.zip'
      17     }
      18    
      19 )
      20 
      21 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
      • Python lambda code

           1 import boto3
           2 import json
           3 import re 
           4 
           5 def lambda_handler(event, context):
           6     product_id_str = event['product_id_str']
           7     S3_BUCKET = 'aws-tc-largeobjects'
           8     S3_FILE = 'DEV-AWS-MO-Building_2.0/my_json_lines.jsonl'
           9 
          10     s3 = boto3.client('s3')
          11 
          12     r = s3.select_object_content(
          13             Bucket=S3_BUCKET,
          14             Key=S3_FILE,
          15             ExpressionType='SQL',
          16             Expression="select s.review_headline, s.review_body, s.star_rating from s3object[*] s where s.product_id = '" + product_id_str + "'",
          17             InputSerialization={'JSON': {"Type": "Lines"}},
          18             OutputSerialization={'JSON': {}}
          19     )
          20     
          21     all_reviews_list = []
          22     helper_format_str = ""
          23     for event in r['Payload']:
          24         if 'Records' in event:
          25             helper_format_str = event['Records']['Payload'].decode('utf-8')
          26             helper_format_str = helper_format_str.replace("review_headline", "review_headline_str").replace("review_body", "review_body_str")
          27             all_reviews_list = helper_format_str.splitlines()
          28             
          29     result_list = []
          30     for review_chunk in all_reviews_list:
          31         result_list.append(json.loads(review_chunk))
          32     
          33     return {
          34         "product_id_str" : product_id_str,
          35         "reviews_arr": result_list
          36     }
        
  • lambda python, checking and extracting info from Bearer token

       1 import json
       2 import base64
       3 
       4 def lambda_handler(event, context):
       5     token_str = ""
       6     ipv4_str = ""
       7     decoded = {}
       8     return_me = {}
       9     name_str = ""
      10     extract_str = ""
      11     cell_str = ""
      12     return_me["message_str"] =  "Report processing, check your phone shortly"
      13     if "Authorization" in json.dumps(event):
      14         #i.e we are at the website and have a valid Bearer token passed
      15         token_str = event["params"]["header"]["Authorization"]
      16         extract_str = token_str.replace("Bearer ", "").strip().split(".")[1]
      17         extract_str += '=' * (-len(extract_str) % 4)
      18         decoded = json.loads(base64.b64decode(extract_str))
      19         cell_str = decoded["phone_number"]
      20         name_str = decoded["cognito:username"]
      21         ipv4_str = event["params"]["header"]["X-Forwarded-For"]
      22         return_me["cell_str"] = cell_str
      23         return_me["name_str"] = name_str
      24         return_me["name_str"] = decoded["cognito:username"]
      25         return_me["ipv4_str"] = ipv4_str
      26         return_me["message_str"] = "Report Processing"
      27     return return_me
    

AWS/LambdaExamples (last edited 2021-07-07 10:24:54 by PieterSmit)