AWS Psycopg2

1.3.8 · active · verified Fri Apr 10

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

Install

Imports

Quickstart

This quickstart demonstrates how to establish a connection to a PostgreSQL database using `aws-psycopg2` in a Lambda-compatible manner. It retrieves database credentials from environment variables, which is a common practice in serverless environments.

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}")

view raw JSON →