Follow dba-ninja.com

Subscribe to RSS feed  Follow @jackvamvas - Twitter

*Use the Comments section for questions

dba-ninja.com Links

Dba_db2_button

Sqlserver_dba_button

Using psycopg2 for PostgreSQL connections via Python on Lambda functions

03 June,2024 by Rambler

Download the psycopg2 library from this link https://github.com/jkehler/awslambda-psycopg2. Follow the instructions in the link . Essentially , you'll need to place the correct folder alongside the lamba_function.py file .  

Initially - I was uploading this package into AWS Lambda and getting an error. Then I found some useful details on https://awstip.com/access-an-amazon-rds-database-using-lambda-function-python-293a014d1cd5 .   

The critical information in the link was "rename _psycopg.cpython-39-x86_64-linux-gnu.so to _psycopg.so" .    Once I renamed the file , uploaded the psycopg2 folder - the python script was able to connect ok

Make sure you reconfigure the default timeout value - read more Task timed out after 3.02 seconds aws lambda

This is the Python sample I executed in the AWS Lambda context 

 

 

import json
import boto3
import psycopg2

username = "my_username"
password = "my_password"
target_host = "my_aws_db_instance_"
db = "postgres"
target_port = "1234"
  
  
 

def lambda_handler(event, context):
  connection = psycopg2.connect(user=username, password=password, host=target_host, database=db, port=target_port)
  cursor = connection.cursor()
  query = "SELECT version() AS version"
  cursor.execute(query)
  results = cursor.fetchone()
  cursor.close()
  connection.commit()
  return results

Author: Rambler (http://www.dba-ninja.com)


Share:

Verify your Comment

Previewing your Comment

This is only a preview. Your comment has not yet been posted.

Working...
Your comment could not be posted. Error type:
Your comment has been posted. Post another comment

The letters and numbers you entered did not match the image. Please try again.

As a final step before posting your comment, enter the letters and numbers you see in the image below. This prevents automated programs from posting comments.

Having trouble reading this image? View an alternate.

Working...

Post a comment on Using psycopg2 for PostgreSQL connections via Python on Lambda functions


dba-ninja.com