这应该能工作吗?当我尝试使用psycopg2运行代码时,似乎什么也没有发生。
我按照以下步骤进行操作:
http://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html
在Amazon Linux实例上,我创建了一个Python 2.7虚拟环境。然后我执行"pip install --upgrade pip"。接着我执行pip install psycopg2,现在我看到了这些文件:(venv27)[ec2-user@ip-172-30-0-194 applyreplyPythonTest]$ ls /home/ec2-user/venv27/lib64/python2.7/site-packages/psycopg2
errorcodes.py extensions.py extras.py __init__.py _ipaddress.py _json.py pool.py psycopg1.py _psycopg.so _range.pyc sql.pyc tz.py
errorcodes.pyc extensions.pyc extras.pyc __init__.pyc _ipaddress.pyc _json.pyc pool.pyc psycopg1.pyc _range.py sql.py tests tz.pyc
(venv27)[ec2-user@ip-172-30-0-194 applyreplyPythonTest]$
我将psycopg2复制到Lambda代码目录的根目录中,其中包含lambda_function.py文件。
#!/usr/bin/python
from __future__ import print_function
import psycopg2
import sys
import pprint
import json
import urllib
import boto3
def getdata():
conn_string = "host='some address' dbname='DBNAME' user='XXXXXXX' password='XXXXXXX'"
# print the connection string we will use to connect
print("Connecting to database\n ->%s" % (conn_string))
# get a connection, if a connect cannot be made an exception will be raised here
print('floob')
conn = psycopg2.connect(conn_string)
print('conn.status', conn.status)
print('conn.server_version', conn.server_version)
# conn.cursor will return a cursor object, you can use this cursor to perform queries
cursor = conn.cursor()
# execute our Query
cursor.execute("SELECT * FROM cognitouser")
# retrieve the records from the database
results = []
for row in cursor.fetchall():
print(row)
#results.append(row)
# print out the records using pretty print
# note that the NAMES of the columns are not shown, instead just indexes.
# for most people this isn't very useful so we'll show you how to return
# columns as a dictionary (hash) in the next example.
#pprint.pprint(records)
def lambda_handler(event, context):
#print("Received event: " + json.dumps(event, indent=2))
getdata()
return json.dumps(event)
我随后会通过S3将我的函数打包为zip文件并上传到AWS。
虽然它运行了,但在Lambda Cloudwatch日志中打印“floob”后没有输出。
我已经独立检查过数据库服务器是可访问的。
有人能建议我可能做错了什么吗?
谢谢。