aws-lambdapsycopg2amazon-rds

No module named 'psycopg2._psycopg': ModuleNotFoundError in AWS Lambda


I have created a deployment package for AWS Lambda with my python file and the dependencies including sqlalchemy and psycopg2. The code works perfectly in accessing the DB locally. But when I imported this zip file, I am getting the following error.

No module named 'psycopg2._psycopg': ModuleNotFoundError

The stack trace of the error is,

{
  "errorMessage": "No module named 'psycopg2._psycopg'",
  "errorType": "ModuleNotFoundError",
  "stackTrace": [
    [
      "/var/task/DBAccessLamdaHandler.py",
      50,
      "lambda_handler",
      "engine = create_engine(rds_host)"
    ],
    [
      "/var/task/sqlalchemy/engine/__init__.py",
      387,
      "create_engine",
      "return strategy.create(*args, **kwargs)"
    ],
    [
      "/var/task/sqlalchemy/engine/strategies.py",
      80,
      "create",
      "dbapi = dialect_cls.dbapi(**dbapi_args)"
    ],
    [
      "/var/task/sqlalchemy/dialects/postgresql/psycopg2.py",
      554,
      "dbapi",
      "import psycopg2"
    ],
    [
      "/var/task/psycopg2/__init__.py",
      50,
      "<module>",
      "from psycopg2._psycopg import (                     # noqa"
    ]
  ]
}

Any help is appreciable


Solution

  • The AWS Lambda runtime environment doesn't include the PostgreSQL libraries so you need to include them within your AWS Lambda upload.

    One way to do this is to get them from the jkehler/awslambda-psycopg2 repo at GitHub. Note that you don't need to build this project from scratch as the repo includes a pre-built package in the psycopg2 folder that you can simply include in your Lambda upload.