Recently while working on an AWS Lambda function written in Python which uses PostgreSQL connection, I faced the following error.

No module named ‘psycopy2._psycopg’

The program was working properly in my laptop. I have used the most popular Postgres python package psycopg2 as the dependency in my program which works well in my laptop and other projects. But the same package is not working on AWS Lambda.

Root Cause

The psycopg2 python package requires Postgres libraries which is missing in AMI used by the AWS Lambda function.

Solution

There are multiple solutions to this. The easiest solution is to use a pre-compiled package aws-psycopg2 which has the required libraries. The package is present in the PyPi repository.

pip install aws-psycopg2

After this, just do the import of psycopg2 as usual in your program. Sample import is given below.

import psycopg2

With this package, my Lambda function started working perfectly.

I hope this tip is useful. Feel free to comment if you have any queries or feedbacks.

Advertisement