python中的AWS Lambda导入模块错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35340921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:19:36  来源:igfitidea点击:

AWS Lambda import module error in python

pythonamazon-web-servicesaws-lambda

提问by Nithin K Anil

I am creating a AWS Lambda python deployment package. I am using one external dependency requests . I installed the external dependency using the AWS documentation http://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html. Below is my python code.

我正在创建一个 AWS Lambda python 部署包。我正在使用一个外部依赖请求。我使用 AWS 文档http://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html安装了外部依赖项。下面是我的python代码。

import requests

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)
        s3.download_file(bucket,key, '/tmp/data.txt')
        lines = [line.rstrip('\n') for line in open('/tmp/data.txt')]
        for line in lines:
            col=line.split(',')
            print(col[5],col[6])
        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

Created the Zip the content of the project-dir directory and uploaded to the lambda(Zip the directory content, not the directory). When I am execute the function I am getting the below mentioned error.

创建压缩 project-dir 目录的内容并上传到 lambda(压缩目录内容,而不是目录)。当我执行该函数时,我收到了下面提到的错误。

START RequestId: 9e64e2c7-d0c3-11e5-b34e-75c7fb49d058 Version: $LATEST
**Unable to import module 'lambda_function': No module named lambda_function**

END RequestId: 9e64e2c7-d0c3-11e5-b34e-75c7fb49d058
REPORT RequestId: 9e64e2c7-d0c3-11e5-b34e-75c7fb49d058  Duration: 19.63 ms  Billed Duration: 100 ms     Memory Size: 128 MB Max Memory Used: 9 MB

Kindly help me to debug the error.

请帮我调试错误。

采纳答案by Nithin K Anil

Error was due to file name of the lambda function. While creating the lambda function it will ask for Lambda function handler. You have to name it as your Python_File_Name.Method_Name. In this scenario I named it as lambda.lambda_handler (lambda.py is the file name).

错误是由于 lambda 函数的文件名造成的。在创建 lambda 函数时,它将要求 Lambda 函数处理程序。您必须将其命名为Python_File_Name.Method_Name。在这种情况下,我将其命名为 lambda.lambda_handler(lambda.py 是文件名)。

Please find below the snapshot. enter image description here

请在快照下方找到。 在此处输入图片说明

回答by user3303554

I found Nithin's answer very helpful. Here is a specific walk-through:

我发现 Nithin 的回答非常有帮助。下面是一个具体的演练:

Look-up these values:

查找这些值:

  1. The name of the lambda_handler function in your python script. The name used in the AWS examples is "lambda_handler" looking like "def lambda_handler(event, context)". In this case, the value is "lambda_handler"
  2. In the Lambda dashboard, find the name of the Handler in the "Handler" text-box in the "Configuration" section in the lambda dashboard for the function (shown in Nithin's screenshot). My default name was "lambda_function.lambda_handler".
  3. The name of your python script. Let's say it's "cool.py"
  1. python 脚本中 lambda_handler 函数的名称。AWS 示例中使用的名称是“lambda_handler”,看起来像“def lambda_handler(event, context)”。在这种情况下,该值为“lambda_handler”
  2. 在 Lambda 仪表板中,在函数的 lambda 仪表板的“配置”部分的“处理程序”文本框中找到处理程序的名称(如 Nithin 的屏幕截图所示)。我的默认名称是“lambda_function.lambda_handler”。
  3. 你的python脚本的名称。假设它是“cool.py”

With these values, you would need to rename the handler (shown in the screenshot) to "cool.lambda_handler". This is one way to get rid of the "Unable to import module 'lambda_function'" errorMessage. If you were to rename the handler in your python script to "sup" then you'd need to rename the handler in the lambda dashboard to "cool.sup"

使用这些值,您需要将处理程序(如屏幕截图所示)重命名为“cool.lambda_handler”。这是摆脱“无法导入模块'lambda_function'”错误消息的一种方法。如果您要将 Python 脚本中的处理程序重命名为“sup”,那么您需要将 lambda 仪表板中的处理程序重命名为“cool.sup”

回答by Catalin Ciurea

Another source of this problem is the permissions on the file that is zipped. It MUSTbe at least world-wide readable. (min chmod 444)

此问题的另一个来源是压缩文件的权限。它必须至少在全球范围内可读。(分钟chmod 444)

I ran the following on the python file before zipping it and it worked fine.

我在压缩之前在 python 文件上运行了以下内容,它工作正常。

chmod u=rwx,go=r

回答by joarleymoraes

There are just so many gotchaswhen creating deployment packages for AWS Lambda (for Python). I have spent hours and hours on debugging sessions until I found a formula that rarely fails.

只是有这么多陷阱的AWS LAMBDA(对于Python)创建部署软件包时。我花了几个小时在调试会话上,直到我找到一个很少失败的公式。

I have created a script that automates the entire process and therefore makes it less error prone. I have also wrote tutorial that explains how everything works. You may want to check it out:

我创建了一个脚本,可以自动执行整个过程,从而减少出错的可能性。我还写了教程,解释了一切是如何工作的。你可能想看看:

Hassle-Free Python Lambda Deployment [Tutorial + Script]

轻松的 Python Lambda 部署 [教程 + 脚本]

回答by 2ank3th

If you are uploading a zip file. Make sure that you are zipping the contents of the directory and not the directory itself.

如果您要上传 zip 文件。确保您正在压缩目录的内容而不是目录本身。

回答by KApuri

I found this hard way after trying all of the solutions above. If you're using sub-directories in the zip file, ensure you include the __init__.pyfile in each of the sub-directories and that worked for me.

在尝试了上述所有解决方案后,我发现这很难。如果您在 zip 文件中使用子目录,请确保将__init__.py文件包含在每个子目录中并且对我有用。

回答by Joe

I had the error too. Turn out that my zip file include the code parent folder. When I unzipand inspect the zip file, the lambda_functionfile is under parent folder ./lambda.

我也有错误。原来我的 zip 文件包含代码父文件夹。当我unzip检查 zip 文件时,该lambda_function文件位于 parent folder 下./lambda

Use the zipcommand, fix the error:

使用zip命令,修复错误:

zip -r ../lambda.zip ./*

回答by uzu

No need to do that mess.

没必要搞那么乱。

use python-lambda

使用 python-lambda

https://github.com/nficano/python-lambda

https://github.com/nficano/python-lambda

with single command pylambda deployit will automatically deploy your function

使用单个命令pylambda deploy,它将自动部署您的功能

回答by Nadeem

I ran into the same issue, this was an exercise as part of a tutorial on lynda.com if I'm not wrong. The mistake I made was not selecting the runtime as Python 3.6 which is an option in the lamda function console.

我遇到了同样的问题,如果我没记错的话,这是 lynda.com 上教程的一部分。我犯的错误是没有将运行时选择为 Python 3.6,这是 lamda 函数控制台中的一个选项。

回答by Uri Goren

You need to zip all the requirements, use this script

您需要压缩所有要求,使用此脚本

#!/usr/bin/env bash
rm package.zip
mkdir package
pip install -r requirements.txt --target package
cat  > package/lambda_function.py
cd package
zip -r9 "../package.zip" .
cd ..
rm -rf package

use with:

与:

package.sh <python_file>