skip to Main Content

Using Python 3.12 and AWS Lambda, I’m trying to run Redis, but it gives an error for an unrecognized library.

It’s hard to believe that Redis is not a native Lambda library. Do I need to upload the Redis library manually, or is it under another name?

import json
import redis

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

Error message:

Response
{
  "errorMessage": "Unable to import module 'lambda_function': No module named 'redis'",
  "errorType": "Runtime.ImportModuleError",
  "requestId": "xxxx-xxx-xxxx-xxxx-xxx",
  "stackTrace": []
}

2

Answers


  1. That’s correct. AWS Lambda Runtime goes with a minimal set of pre-installed libraries.

    However, you can include any libraries you’re using.

    > cd path/to/project/root               # Navigate to your project root
    > mkdir package                         # Create a directory for dependencies
    > pip install --target ./package redis  # Install dependencies into separated direcotry
    > zip -r ../lambda_src.zip .            # Create an archive with source code and upload it to AWS
    

    Please take into account that depending on your set up these steps may differ. For example if you’re using serverless to manage Lambda functions you may use built-in support for packaging python projects with preferred dependency manager, e.g pipenv, poetry.

    I hope it helps, please let me know if you have further questions.

    Links:

    Login or Signup to reply.
  2. Correct, you can create redis layer and attach with your lambda function to resolve the issue.

    mkdir packages
    cd packages
    python3 -m venv venv
    source venv/bin/activate
     
    mkdir python
    cd python
    pip install redis -t .
     
    rm -rf *dist-info
    cd..
    zip -r requirements-package.zip python
    

    Next, return to Lambda and navigate to Layers. Create a new layer and name it ‘redis-layer.’ Upload the ZIP file.

    Once you have created the layer, add it to your Lambda function.

    Or else you can directly install dependencies into your project folder and you can upload a zip

    open your project directory and create requirements.txt file and add all dependencies that you required for your function.

    run:

    pip install -r requirements.txt -t .
    zip -r myfunction.zip .
    

    Upload a zip to your lambda function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search