[英]Importing a package from AWS lambda temp directory in Python 3.8
The problem I have is similar to this SO question but the answer doesn't work for me.我遇到的问题类似于这个SO question ,但答案对我不起作用。 I am trying to import Python library (let's say
xgboost
) from /tmp
folder in AWS Lambda.我正在尝试从 AWS Lambda 中的
/tmp
文件夹导入 Python 库(比如说xgboost
)。
Library requests
is added to Lambda layer and what I did is:库
requests
被添加到 Lambda 层,我所做的是:
import json
import io
import os
import zipfile
import requests
import sys
sys.path.insert(0, '/tmp/')
sys.path.append('/tmp/')
os.environ["PYTHONPATH"] = "/var/task"
def get_pkgs(url):
print("Getting Packages...")
re = requests.get(url)
z = zipfile.ZipFile(io.BytesIO(re.content))
print("Extracting Packages...")
z.extractall("/tmp/")
print("Packages are downloaded and extracted.")
def attempt_import():
print("="*50)
print("ATTEMPT TO IMPORT DEPENDENCIES...")
print("="*50)
import xgboost
print("IMPORTING DONE.")
def main():
URL = "https://MY_BUCKET.s3.MY_REGION.amazonaws.com/MY_FOLDER/xgboost/xgboost.zip"
get_pkgs(URL)
attempt_import()
def lambda_handler(event, context):
main()
return "Hello Lambda"
The error I get is [ERROR] ModuleNotFoundError: No module named 'xgboost'
.我得到的错误是
[ERROR] ModuleNotFoundError: No module named 'xgboost'
。 I gave my S3 bucket all necessary permissions, and I am positive that Lambda can access the .zip
file since the requests.get
works and variable z
returns:我给了我的 S3 存储桶所有必要的权限,并且我确信 Lambda 可以访问
.zip
文件,因为requests.get
有效并且变量z
返回:
<zipfile.ZipFile file=<_io.BytesIO object at 0x7fddaf31c400> mode='r'>
You could try using the boto3 library to download the file from S3 to /tmp directory as explained in https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.download_file您可以尝试使用 boto3 库将文件从 S3 下载到 /tmp 目录,如https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client 中所述。下载文件
import boto3
s3 = boto3.resource('s3')
s3.meta.client.download_file('mybucket', 'hello.txt', '/tmp/hello.txt')
Actually, my code above works and I had a rather silly error.实际上,我上面的代码有效,但我遇到了一个相当愚蠢的错误。 Instead of zipping the
xgboost
package folders ( xgboost
, xgboost.libs
and xgboost.dist-info
) I actually zipped their parental folder which I named package-xgoboost
, and that didn't worked in AWS lambda.而不是压缩
xgboost
package 文件夹( xgboost
, xgboost.libs
和xgboost.dist-info
)我实际上压缩了我命名为package-xgoboost
的父文件夹,但这在 AWS Z945F3FC449518A73B6F5F32868.DB46 中不起作用Be sure that you actually zip those 3 folders directly.确保您实际上是 zip 这三个文件夹直接。
Also, make sure your xgboost
library is up-to-date.此外,请确保您的
xgboost
库是最新的。 Previously I used version 1.2.1 which didn't work either.以前我使用的版本 1.2.1 也不起作用。 Upgrading the library and zipping the newest
xgboost
version (in my case 1.3.3) finally worked.升级库并压缩最新的
xgboost
版本(在我的例子中是 1.3.3)终于奏效了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.