Kaguei Nakueka
Kaguei Nakueka

Reputation: 1128

AWS Lambda Function (Python) - How to use external libraries?

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?

Upvotes: 2

Views: 2692

Answers (1)

Caldazar
Caldazar

Reputation: 3802

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

Upvotes: 3

Related Questions