简体   繁体   English

没有名为“psycopg2._psycopg”的模块:AWS Lambda 中的 ModuleNotFoundError

[英]No module named 'psycopg2._psycopg': ModuleNotFoundError in AWS Lambda

I have created a deployment package for AWS Lambda with my python file and the dependencies including sqlalchemy and psycopg2.我已经使用我的 python 文件和包括 sqlalchemy 和 psycopg2 的依赖项为 AWS Lambda 创建了一个部署 package。 The code works perfectly in accessing the DB locally.该代码在本地访问数据库方面非常有效。 But when I imported this zip file, I am getting the following error.但是当我导入这个 zip 文件时,出现以下错误。

No module named 'psycopg2._psycopg': ModuleNotFoundError

The stack trace of the error is,错误的堆栈跟踪是,

{
  "errorMessage": "No module named 'psycopg2._psycopg'",
  "errorType": "ModuleNotFoundError",
  "stackTrace": [
    [
      "/var/task/DBAccessLamdaHandler.py",
      50,
      "lambda_handler",
      "engine = create_engine(rds_host)"
    ],
    [
      "/var/task/sqlalchemy/engine/__init__.py",
      387,
      "create_engine",
      "return strategy.create(*args, **kwargs)"
    ],
    [
      "/var/task/sqlalchemy/engine/strategies.py",
      80,
      "create",
      "dbapi = dialect_cls.dbapi(**dbapi_args)"
    ],
    [
      "/var/task/sqlalchemy/dialects/postgresql/psycopg2.py",
      554,
      "dbapi",
      "import psycopg2"
    ],
    [
      "/var/task/psycopg2/__init__.py",
      50,
      "<module>",
      "from psycopg2._psycopg import (                     # noqa"
    ]
  ]
}

Any help is appreciable任何帮助都是可观的

The AWS Lambda runtime environment doesn't include the PostgreSQL libraries so you need to include them within your AWS Lambda upload. AWS Lambda 运行时环境不包含 PostgreSQL 库,因此您需要将它们包含在您的 AWS Lambda 上传中。

One way to do this is to get them from the jkehler/awslambda-psycopg2 repo at GitHub.一种方法是从 GitHub 的jkehler/awslambda-psycopg2 存储库中获取它们。 Note that you don't need to build this project from scratch as the repo includes a pre-built package in the psycopg2 folder that you can simply include in your Lambda upload.请注意,您不需要从头开始构建此项目,因为 repo 在psycopg2 文件夹中包含一个预构建的包,您可以简单地将其包含在您的 Lambda 上传中。

The psycopg2 build library from jkehler/awslambda-psycopg2 was built for python 3.6 and make sure that while uploading your code to AWS lambda, select Python Runtime environment as 3.6, and it should work. jkehler/awslambda-psycopg2中的 psycopg2 构建库是为 python 3.6 构建的,并确保在将代码上传到 AWS lambda 时,选择 Python Runtime environment 作为 3.6,它应该可以工作。 I banged my head on this for a full day and then when i changed to 3.6, the import error just vanished.我为此苦苦挣扎了一整天,然后当我更改为 3.6 时,导入错误就消失了。

If you are going to attempt to build it yourself, remember that you must build on a machine or VM with the same architecture as your target at AWS .如果您打算自己构建它, 请记住,您必须在与 AWS 的目标具有相同架构的机器或 VM 上构建它。

Latest as of 26/MAR/2020最新截至 2020 年 3 月 26 日

I was skeptical about depending on a third-party library for my production code.我对我的生产代码依赖第三方库持怀疑态度。 On research the following works,在研究以下工作时,

The issue happens only when the packages are built from MAC OS.仅当从 MAC OS 构建软件包时才会出现此问题。

I can confirm today that the issue is fixed when I build the package from Centos 7 ( AWS AMI )我今天可以确认,当我从 Centos 7 ( AWS AMI ) 构建软件包时问题已得到解决

The following is my approach以下是我的做法

requirement.txt需求.txt

psycopg2-binary==2.8.4

Build process构建过程

pip install -r requirements.txt --target .

Lambda code is in the root directory Lambda 代码位于根目录中

+-- lambda_function.py
+-- psycopg2
    +-- psycopg2 files

Zip the directory and test the code in lambda works.压缩目录并测试 lambda 中的代码是否有效。

The only additional step is to build the package in Linux env instead of macOS using the Docker container.唯一的额外步骤是使用 Docker 容器在 Linux 环境而不是 macOS 中构建包。 An example can be found here: Deploy AWS Amplify Python Lambda from macOS with Docker可以在此处找到示例: 使用 Docker 从 macOS 部署 AWS Amplify Python Lambda

For Windows (Looks like in any OS which is not build on Amazon AMI or Centos), the easiest fix is to use对于 Windows(看起来像在任何不是在 Amazon AMI 或 Centos 上构建的操作系统),最简单的修复是使用

psycopg2 Python Library for AWS Lambda适用于 AWS Lambda 的 psycopg2 Python 库

which you can find https://github.com/jkehler/awslambda-psycopg2你可以找到https://github.com/jkehler/awslambda-psycopg2

Like other answers, psycopg2-binary worked fine for python3.9 (it looks like other package awslambda-psycopg2 was only available for python3.6).与其他答案一样,psycopg2-binary 对 python3.9 运行良好(看起来其他包awslambda-psycopg2仅适用于 python3.6)。

But, if you run on MacOs before sending to aws lambda, you must specify the platform to your pip install like this:但是,如果您在发送到 aws lambda 之前在 MacOs 上运行,则必须为您的 pip 安装指定平台,如下所示:

pip3.9 install --platform=manylinux1_x86_64 --only-binary=:all: psycopg2-binary

instead of using psycopg2, try using pg8000 in command prompt go the directory that you are currently working(example F:\example) pip install pg8000 -t.不要使用 psycopg2,而是尝试在命令提示符下使用 pg8000 转到您当前正在工作的目录(例如 F:\example) pip install pg8000 -t。 (-t. is for installing pg8000 in the directory that you are working) (-t. 用于在您正在工作的目录中安装 pg8000)

// handler.py import pg8000 // handler.py 导入 pg8000

database=''
host=''
port=''
user=''
password=''
conn = pg8000.connect(database=database, host=host, port=port, user=user, 
password=password)

def lambda_function(event, context):
   .
   .
   .

after writing your code zip the code and upload in your aws lambda.编写代码后压缩代码并上传到您的 aws lambda。

It worked for me!!!它对我有用!!!

I've had issues getting SQLAlchemy to run on AWS Lambda despite the fact that I have tried multiple psycopg2 versions, but what eventually solved it for me was to use an older Python version.尽管我尝试了多个 psycopg2 版本,但让 SQLAlchemy 在 AWS Lambda 上运行时遇到问题,但最终为我解决的问题是使用较旧的 Python 版本。 I went from Python 3.9 to 3.7 and it was finally able to run (Using psycopg2-binary 2.8.4, but I didn't try other versions or the none binary version with 3.7)我从 Python 3.9 转到 3.7,它终于能够运行(使用 psycopg2-binary 2.8.4,但我没有尝试其他版本或 3.7 的无二进制版本)

Thanks to AWS Lambda Layers we can include a ready compiled psycopg2 layer for our selected Python versions directly to our Lambda function.多亏了AWS Lambda 层,我们可以为我们选择的 Python 版本直接包含一个已编译好的psycopg2 层到我们的 Lambda 函数中。 Please use the version you need from this Github repo .请使用此Github repo中您需要的版本。 Be careful to use the correct Python version and Region in Lambda and layer creation.请注意在 Lambda 和层创建中使用正确的 Python 版本和区域。

I have faced a similar issue.我遇到了类似的问题。 I tried to create the layers using AWS Cloud shell it worked with Python3.8 .我尝试使用与 Python3.8 一起使用的AWS Cloud shell Python3.8图层。 But failed in Python3.9 though.但是在Python3.9中失败了。

Please change the region name as per your AWS Region请根据您的 AWS 区域更改区域名称

sudo amazon-linux-extras install python3.8

curl -O https://bootstrap.pypa.io/get-pip.py

python3.8 get-pip.py --user

mkdir python

python3.8 -m pip install --platform=manylinux1_x86_64 --only-binary=:all: pandas numpy pymysql psycopg2-binary SQLAlchemy -t python/

zip -r layer.zip python

aws lambda publish-layer-version \
 --layer-name mics-layer \
 --description "Pandas Numpy psycopg2-binary SQLAlchemy pymysql" \
 --zip-file fileb://layer.zip \
 --compatible-runtimes python3.8 python3.9 \
 --region eu-west-1

In CDK you can use something like this.在 CDK 中你可以使用这样的东西。 Take in consideration that this only works in Python 3.8 .考虑到这仅适用于Python 3.8

    sqlachemy_layer = lambda_.LayerVersion(
        scope=self,
        id=LAYERS_SQLALCHEMY_LAYER,
        layer_version_name=LAYERS_SQLALCHEMY_LAYER,
        code=lambda_.Code.from_asset(
            str(pathlib.Path(__file__).parent.joinpath("dependencies").resolve()),
            bundling=BundlingOptions(
                image=lambda_.Runtime.PYTHON_3_8.bundling_image,
                command=[
                    "bash", "-c",
                    "pip install -r requirements-sqlalchemy.txt -t /asset-output/python && cp -au . /asset-output/python",
                ]
            )
        ),
        compatible_runtimes=[
            lambda_.Runtime.PYTHON_3_8,
        ],
    )

The requirements-sqlalchemy.txt:要求-sqlalchemy.txt:

psycopg2-binary
sqlalchemy

And the file structure:和文件结构:

  • dependencies/依赖项/
    • requirements-sqlalchemy.txt要求-sqlalchemy.txt
  • my_stack.py我的堆栈.py

The latest update to psycopg (when I answered this), fixes this. psycopg 的最新更新(当我回答这个问题时)修复了这个问题。 You need to do update the version for psycopg2-binary to 2.8.4.您需要将 psycopg2-binary 的版本更新为 2.8.4。 That did the trick for me.这对我有用。

psycopg2-binary==2.8.4

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AWS Lambda 层:没有名为“psycopg2._psycopg”的模块” - AWS Lambda Layer: No module named 'psycopg2._psycopg'" 无法导入模块“lambda_function”:没有名为“psycopg2._psycopg aws lambda 函数”的模块 - Unable to import module 'lambda_function': No module named 'psycopg2._psycopg aws lambda function AWS Lambda - 无法导入模块“main”:没有名为“psycopg2”的模块 - AWS Lambda - Unable to import module 'main': No module named 'psycopg2' 错误:使用 python 3.8.7 版本的 AWS Lambda 中没有名为“psycopg2.__psycopg”的模块 - Error: No Module Named 'psycopg2.__psycopg' in AWS Lambda with python 3.8.7 version 没有名为“psycopg2”的模块-如何在具有 CloudFormation 的 AWS Lambda 中使用 python 库? - No module named 'psycopg2' - how to use python library in an AWS Lambda with CloudFormation? lambda python function 带有外部库 psycopg2 - 没有名为 psycopg2 的模块 - lambda python function with external library psycopg2 - No module named psycopg2 使用psycopg2的AWS Lambda问题 - AWS Lambda issue with psycopg2 AWS Lambda psycopg2 层 - AWS Lambda layer for psycopg2 构建 lambda function 以连接到 Postgresql 获取:无法导入模块“lambda_function”:没有名为“psycopg2”的模块 - Building lambda function to connect to Postgresql getting :Unable to import module 'lambda_function': No module named 'psycopg2' PostgreSQL无法使用psycopg2在AWS Lambda上的Python中插入 - PostgreSQL not INSERTing in Python on AWS Lambda with psycopg2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM