Home > Back-end >  Lambda function python script using psycopg2
Lambda function python script using psycopg2

Time:10-20

Full screenshot

Runtime settings

I am going to connect RDS postgresql Database using Lambda function (python script) I attached screenhot. The error logs here. Unable to import module 'postgres_test': No module named 'psycopg2'

python version is 3.6

This issue causing due to not installed psycopg2 package. Then I don't know how can I install the package on lambda Pls guide me for it.

postgres_test.py:

`

import sys
import logging
import psycopg2

from db_util import make_conn, fetch_data
def lambda_handler(event, context):
query_cmd = "select count(*) from tablename"
# print query_cmd

# get a connection, if a connect cannot be made an exception will be raised here
conn = make_conn()

result = fetch_data(conn, query_cmd)
conn.close()

return result

db_util.py:

` ​

   ​import psycopg2

   ​db_host = "db_host" 
   ​db_port = 5432
   ​db_name = "db_name "
   ​db_user = "db_user "
   ​db_pass = "db_pass "
   ​db_table = "users"


   ​def make_conn():
       ​conn = None
       ​try:
           ​conn = psycopg2.connect("dbname='%s' user='%s' host='%s' 
   ​password='%s'" % (db_name, db_user, db_host, db_pass))
       ​except:
           ​print "I am unable to connect to the database"return conn


   ​def fetch_data(conn, query):
       ​result = []
       ​print "Now executing: %s" % (query)
       ​cursor = conn.cursor()
       ​cursor.execute(query)

       ​raw = cursor.fetchall()
       ​for line in raw:
           ​result.append(line)

       ​return result

CodePudding user response:

To work with different libraries in lambda you have to install the library in the current project and upload it as zip file to lambda.

Specific to psycopg2 use this repo https://github.com/jkehler/awslambda-psycopg2

And to install some other library use the below command
For example requests library

pip install requests -t .

Your project will look something like below

.
├── lambda_function.py
├── psycopg2
├── <library2>

To upload a project to lambda using zip file method you can use the following links

https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-package.html https://alexharv074.github.io/2018/08/18/creating-a-zip-file-for-an-aws-lambda-python-function.html

  • Related