Skip to content

Instantly share code, notes, and snippets.

@agraebe
Created January 8, 2020 23:12
Show Gist options
  • Save agraebe/a72235359bf5ba102ad77730ce1bf437 to your computer and use it in GitHub Desktop.
Save agraebe/a72235359bf5ba102ad77730ce1bf437 to your computer and use it in GitHub Desktop.
Psycopg2 Aurora Connection Example
import psycopg2
Import os
DB_HOST = os.getenv("DB_HOST")
DB_PORT = os.getenv("DB_PORT")
DB_USER = os.getenv("DB_USER")
DB_PW = os.getenv("DB_PW")
DB_NAME = os.getenv("DB_NAME")
def lambda_handler(event, context):
global db_conn
try:
# use very short connect_timeout!
db_conn = psycopg2.connect(host=DB_HOST, port=DB_PORT,
user=DB_USER, password=DB_PW,
database=DB_NAME, connect_timeout=2)
except Exception as err:
logger.exception("Could not connect to database! %s", err)
# errors result in lambda failures to apply retry strategies
sys.exit()
with db_conn.cursor() as cursor:
cursor.execute("SELECT 1")
result = cursor.fetchone()
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment