2

I am trying to create a Lambda function (Python) with the code below:

import json
import qrcode
from PIL import Image, ImageDraw
import boto3

def lambda_handler(event, context):
    
    input_data = "https://m.media-amazon.com/images/I/81xuW7h1tkL._AC_SL1500_.jpg"
    qr = qrcode.QRCode(
            version=1,
            box_size=10,
            border=5)
    qr.add_data(input_data)
    qr.make(fit=True)
    img = qr.make_image(fill='black', back_color='white')
    file_name = "qrcode001.png"
    img.save(file_name)
    string = "WhatAmIGoodFor"
    encoded_string = string.encode("utf-8")
    bucket_name = "mys3bucket"
    s3_path = "qrcode/" + file_name
    s3 = boto3.resource("s3")
    s3.Bucket(bucket_name).put_object(Key=s3_path, Body=encoded_string)

    
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

I installed all modules need in the same folder as below:

enter image description here

And created it via CLI as below:

aws lambda create-function --function-name generate_ticket \
--zip-file fileb://Archive.zip --handler lambda_function.lambda_handler --runtime python3.9 \
--role arn:aws:iam::999999999:role/service-role/generate_ticket-role-hj1kcybi

enter image description here

How can I correctly use external libraries in my Lambda function?

3
  • In the context of Python "lambda" has a different meaning than in the context am AWS. You should make your context more clear! Commented Feb 2, 2022 at 10:03
  • Do you mean the title? I have updated it anyways :-) Commented Feb 2, 2022 at 10:05
  • Kaguei for you Klaus Commented Feb 2, 2022 at 10:28

1 Answer 1

3

Python modules should not be in a folder. They should be at the same level as lambda_function.py and then you zip them all together.

If you don't have many dependencies, this is ok, but with more additional libraries, your cold start of lambda function will be slower, so it's preferable to create a lambda layer that will contain your dependencies and attach that layer to the lambda function. For configuration of layers, you can see details in the official documentation

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.