我將使用附帶的Lambda函數(shù)(python腳本連接RDS postgresql數(shù)據(jù)庫(kù)。錯(cuò)誤記錄在這里。Unable to import module 'postgres_test': No module named 'psycopg2'
python版本是3.6
此問(wèn)題是由于未安裝psycopg2軟件包而導(dǎo)致的。那么我不知道如何在lambda上安裝軟件包,請(qǐng)指導(dǎo)我。
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
要使用lambda中的不同庫(kù),您必須在當(dāng)前項(xiàng)目中安裝庫(kù),并將其作為zip文件上載到lambda。
特定于psycopg2使用此repohttps://github.com/jkehler/awslambda-psycopg2
要安裝其他庫(kù),請(qǐng)使用下面的命令,例如
requests
library您的項(xiàng)目將如下所示
要使用zip文件方法將項(xiàng)目上載到lambda,可以使用以下鏈接
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