python - 使用 psycopg2 和 Lambda 更新 Redshift (Python)

标签 python amazon-web-services aws-lambda amazon-redshift aws-sdk

我正在尝试使用 python 从 Lambda 函数更新 Redshift。为此,我试图合并 2 个代码片段。当我分别运行这两个片段时,它们都可以正常工作。

  1. 从 PyDev 为 Eclipse 更新 Redshift

    import psycopg2
    
    conn_string = "dbname='name' port='0000' user='name' password='pwd' host='url'"
    conn = psycopg2.connect(conn_string)
    
    cursor = conn.cursor()
    
    cursor.execute("UPDATE table SET attribute='new'")
    conn.commit()
    cursor.close()
    
  2. 接收上传到 S3 存储桶的内容(Lambda 上可用的预构建模板)

    from __future__ import print_function
    
    import json
    import urllib
    import boto3
    
    print('Loading function')
    
    s3 = boto3.client('s3')
    
    
    def lambda_handler(event, context):
        #print("Received event: " + json.dumps(event, indent=2))
    
        # Get the object from the event and show its content type
        bucket = event['Records'][0]['s3']['bucket']['name']
        key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8')
    
        try:
            response = s3.get_object(Bucket=bucket, Key=key)
            print("CONTENT TYPE: " + response['ContentType'])
            return response['ContentType']
    
        except Exception as e:
            print(e)
            print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
            raise e
    

由于这两个部分都有效,我尝试将它们组合起来,以便在将文件上传到 s3 时更新 Redshift:

from __future__ import print_function

import json
import urllib
import boto3
import psycopg2

print('Loading function')

s3 = boto3.client('s3')


def lambda_handler(event, context):
    #print("Received event: " + json.dumps(event, indent=2))

    # Get the object from the event and show its content type
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8')

    conn_string = "dbname='name' port='0000' user='name' password='pwd' host='url'"

    conn = psycopg2.connect(conn_string)

    cursor = conn.cursor()

    cursor.execute("UPDATE table SET attribute='new'")
    conn.commit()
    cursor.close()

    try:
        response = s3.get_object(Bucket=bucket, Key=key)
        print("CONTENT TYPE: " + response['Body'].read())
        return response['Body'].read()
    except Exception as e:
        print(e)
        print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
        raise e

由于我使用的是外部库,因此我需要创建一个部署包。我创建了一个新文件夹 (lambda_function1) 并将我的 .py 文件 (lambda_function1.py) 移动到该文件夹​​。我运行以下命令在该文件夹中安装 psycopg2:

pip install psycopg2 -t \lambda_function1

我收到以下反馈:

Collecting psycopg2
  Using cached psycopg2-2.6.1-cp34-none-win_amd64.whl
Installing collected packages: psycopg2
Successfully installed psycopg2-2.6.1 

然后我压缩了目录的内容。并将该 zip 上传到我的 lambda 函数。当我将文档上传到函数监控的存储桶时,我的 cloudwatch 日志中收到以下错误:

Unable to import module 'lambda_function1': No module named _psycopg 

当我查看库时,唯一名为“_psycopg”的东西是“_psycopg.pyd”。

是什么导致了这个问题?当我使用 3.4 时 Lambda 使用 Python 2.7 是否重要?我在 Windows 机器上压缩文件内容是否重要?有没有人能够从 lambda 成功连接到 Redshift?

最佳答案

为了让它工作,您需要使用静态链接的libpq.so 库构建psycopg2。查看此 repo https://github.com/jkehler/awslambda-psycopg2 .它已经构建了 psycopg2 包并说明了如何自己构建它。

回到你的问题:

是什么导致了这个问题?

psycopg2 需要使用适用于 Linux 的静态链接库构建和编译。

当我使用 3.4 时,Lambda 使用 Python 2.7 是否重要?

是的,lambda 只支持 2.7 版本。只需创建虚拟环境并在其中安装所有必需的包。

我在 Windows 机器上压缩我的文件内容有什么关系吗?

只要你压缩的所有库都可以在 Linux 上运行它就不行

有没有人能够从 lambda 成功连接到 Redshift?

是的。

关于python - 使用 psycopg2 和 Lambda 更新 Redshift (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36607952/

相关文章:

python 谷歌应用程序引擎编程

python - 生成序列的字符数

amazon-s3 - 如何使用aws lambda将存储在S3中的数据写入Dynamodb

python - 如何在 python 中查询 AWS DynamoDB?

python - 从模块导入多个类的语法

python - Matlab 向量化 printf 类似 python 中的函数

amazon-web-services - 我如何确认来自Amazon SNS的订阅请求HTTP

c# - 如何从 S3 获取 GetObjectResponse 的字节?

amazon-web-services - 如何在SAM模板中动态传递codeUri

node.js - AWS Lambda 安全 - 默认访问 Cognito?