简体   繁体   English

使用 Python 为 AWS Lambda 构建 Docker 容器时出现导入模块错误

[英]Import Module Error when building a Docker Container with Python for AWS Lambda

I'm trying to build a Docker container that runs Python code on AWS Lambda.我正在尝试构建一个在 AWS Lambda 上运行 Python 代码的 Docker 容器。 The build works fine, but when I test my code, I get the following error:构建工作正常,但是当我测试我的代码时,我收到以下错误:

{"errorMessage": "Unable to import module 'function': No module named 'utils'", "errorType": "Runtime.ImportModuleError", "stackTrace": []}

I basically have two python scripts in my folder, function.py and utils.py, and I import some functions from utils.py and use them in function.py.我的文件夹中基本上有两个 python 脚本,function.py 和 utils.py,我从 utils.py 中导入一些函数并在 function.py 中使用它们。

Locally, it all works fine, but when I build the Container and test it with the following curl command, I get the above error.在本地,一切正常,但是当我构建容器并使用以下 curl 命令对其进行测试时,出现上述错误。 Test curl command:测试卷曲命令:

curl --request POST \
  --url http://localhost:9000/2015-03-31/functions/function/invocations \
  --header 'Content-Type: application/json' \
  --data '{"Input": 4}'

Here's my dockerfile:这是我的码头文件:

FROM public.ecr.aws/lambda/python:3.7

WORKDIR /

COPY . .

COPY function.py ${LAMBDA_TASK_ROOT}

COPY requirements.txt .

RUN  pip3 install -r requirements.txt --target "${LAMBDA_TASK_ROOT}"

CMD [ "function.lambda_handler" ]

What I read in related Stackoverflow questions is to try importing the functions from utils.py in another way, I've tried changing from utils import * to from .utils import all , I changed the WORKDIR in my Dockerfile, and I put the utils file in a separate utils folder and tried importing this way: from utils.utils import * .我在相关的 Stackoverflow 问题中读到的是尝试以另一种方式从 utils.py 导入函数,我尝试from utils import *更改为from .utils import all ,我在我的 Dockerfile 中更改了 WORKDIR,然后我把 utils将文件放在单独的 utils 文件夹中并尝试以这种方式导入: from utils.utils import * I have also tried running the code in Python 3.8.我也尝试过在 Python 3.8 中运行代码。

Here's my folder structure: Here's my folder structure这是我的文件夹结构:这是我的文件夹结构

Does anyone know what I'm doing wrong?有谁知道我做错了什么?

The Dockerfile statement COPY . . Dockerfile 语句COPY . . COPY . . copies all files to the working directory, which given your previous WORKDIR , is / .将所有文件复制到工作目录,给定您之前的WORKDIR ,是/

To resolve the Python import issue, you need to move the Python module to the right directory:要解决 Python 导入问题,您需要将 Python 模块移动到正确的目录:

COPY utils.py ${LAMBDA_TASK_ROOT}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM