【发布时间】:2019-11-25 10:32:15
【问题描述】:
我在python3.6中编写了lambda函数来访问EC2实例中运行的postgresql数据库。
psycopg2.connect(user="<USER NAME>",
password="<PASSWORD>",
host="<EC2 IP Address>",
port="<PORT NUMBER>",
database="<DATABASE NAME>")
创建了具有所需依赖项的部署包作为 zip 文件并上传到 AWS lambda。为了构建依赖项,我遵循了 THIS 参考指南。
并且还将 虚拟私有云 (VPC) 配置为默认配置,还包括 Ec2 实例详细信息,但我无法从数据库获取连接。尝试从 lambda 连接数据库时导致超时。
Lambda 函数:
from __future__ import print_function
import json
import ast,datetime
import psycopg2
def lambda_handler(event, context):
received_event = json.dumps(event, indent=2)
load = ast.literal_eval(received_event)
try:
connection = psycopg2.connect(user="<USER NAME>",
password="<PASSWORD>",
host="<EC2 IP Address>",
# host="localhost",
port="<PORT NUMBER>",
database="<DATABASE NAME>")
cursor = connection.cursor()
postgreSQL_select_Query = "select * from test_table limit 10"
cursor.execute(postgreSQL_select_Query)
print("Selecting rows from mobile table using cursor.fetchall")
mobile_records = cursor.fetchall()
print("Print each row and it's columns values")
for row in mobile_records:
print("Id = ", row[0], )
except (Exception,) as error :
print ("Error while fetching data from PostgreSQL", error)
finally:
#closing database connection.
if(connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!'),
'dt' : str(datetime.datetime.now())
}
我google了很多,但我找不到任何解决方法。有什么方法可以满足这个要求吗?
【问题讨论】:
标签: postgresql amazon-web-services amazon-s3 aws-lambda amazon-vpc