如何在AWS Lambda上安装psycopg2(Python Postgres驱动程序)?

4

这应该能工作吗?当我尝试使用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”后没有输出。
我已经独立检查过数据库服务器是可访问的。
有人能建议我可能做错了什么吗?
谢谢。

你需要将共享库进行静态链接。请参考这个答案 - skunkwerk
你可以使用原始的psycopg2-binary [distribution](https://dev59.com/nLzpa4cB1Zd3GeqPMH8a#70983576)来适配你的架构。 - Constantine
2个回答

3
我为lambda函数添加了一个包含psycopg2的lambda层。下面是可用的Lambda层列表:https://github.com/jetbridge/psycopg2-lambda-layer 我正在使用serverless框架,这是我的Lambda函数代码:
functions:
  example:
    handler: handler.example
    layers:
      - arn:aws:lambda:us-east-1:898466741470:layer:psycopg2-py37:3
    events:
      - http:
          path: example
          method: post
          authorizer: aws_iam
          cors: true

请澄清一下,由于这是一个层,所以此依赖项无需包含在requirements.txt中,对吗? - Leonardo Wildt

0

三年后,AWS Lambda上的Python 2.7已被弃用。

使用Python 3.x,您可能需要一些步骤来添加此依赖项。

您可以查看[1]以获取有关执行psycopg2的非标准构建的更多信息。

这些是我在EC2实例上使用Amazon Linux 1 AMI构建层zip所使用的bash命令[2]:

$ sudo yum update
$ sudo yum install python36
$ curl -O https://bootstrap.pypa.io/get-pip.py
$ python3 get-pip.py --user
$ sudo yum groupinstall "Development Tools"
$ sudo yum install python36-devel
$ sudo yum install postgresql-devel
$ mkdir -p package/python/lib/python3.6/site-packages/
$ pip3 install psycopg2 -t package/python/lib/python3.6/site-packages/
$ mkdir package/lib
$ sudo find / -name libpq.so*
$ cp /usr/lib64/libpq.so package/lib
$ cp /usr/lib64/libpq.so.5 package/lib
$ cp /usr/lib64/libpq.so.5.5 package/lib
$ cd package
$ zip -r psycopg2.zip *

在Lambda控制台创建层时,您可以使用创建的zip文件。

[1] http://initd.org/psycopg/docs/install.html

[2] https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接