AWS Psycopg2
aws-psycopg2 is a custom-compiled Python package of the popular psycopg2 PostgreSQL adapter, specifically designed for use in AWS Lambda environments. It addresses the common issue of missing PostgreSQL C libraries in the AWS Lambda Amazon Linux AMI by statically linking libpq.so. The library provides a seamless way to connect Python Lambda functions to PostgreSQL databases. It is actively maintained with releases supporting various Python runtime versions. The current version is 1.3.8.
Warnings
- gotcha Standard `pip install psycopg2` or `psycopg2-binary` will likely fail in AWS Lambda functions due to missing underlying C libraries (e.g., libpq.so) in the Lambda execution environment. `aws-psycopg2` specifically solves this by providing a statically linked version.
- gotcha When deploying to AWS Lambda, ensure the Python version of `aws-psycopg2` (or any `psycopg2` layer) matches your Lambda function's runtime. Mismatched Python versions can lead to 'No module named psycopg2._psycopg' or other import errors.
- gotcha Using `aws-psycopg2` (or any `psycopg2` variant) in AWS Lambda often requires packaging it correctly, typically within a Lambda layer or as part of a container image deployment. Simply zipping a local `pip install` from a non-Amazon Linux environment will lead to runtime errors.
Install
-
pip install aws-psycopg2
Imports
- psycopg2
import psycopg2
Quickstart
import psycopg2
import os
host = os.environ.get('DB_HOST', 'localhost')
database = os.environ.get('DB_NAME', 'mydatabase')
user = os.environ.get('DB_USER', 'myuser')
password = os.environ.get('DB_PASSWORD', 'mypassword')
try:
conn = psycopg2.connect(host=host, database=database, user=user, password=password)
cur = conn.cursor()
cur.execute('SELECT version();')
db_version = cur.fetchone()
print(f"PostgreSQL database version: {db_version}")
cur.close()
conn.close()
except Exception as e:
print(f"Error connecting to the database: {e}")