首页 > 解决方案 > 使用 serverless-python-requirements 为无服务器本机编译 python 库

问题描述

我正在尝试从我的 Windows 机器编译 numpy 以用于 AWS Lambda 函数。

我一直在关注这个简单的serverless-python-requirements示例,让 lambda 打印一个 numpy 数组。

serverless deploy从本地目录的 virtualenv 中运行../numpy-test

(numpy-test) C:\Users\...\numpy-test>serverless deploy
Serverless: Generated requirements from C:\Users\...\numpy-test\requirements.txt in C:\Users\...\numpy-test\.serverless\requirements.txt...
Serverless: Installing requirements from C:\Users\...\numpy-test\.serverless\requirements\requirements.txt ...
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Injecting required Python packages to package...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service .zip file to S3 (42.86 MB)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...

我的 requirements.txt 文件只包含

numpy==1.13.1

我的 YML 文件看起来像:

service: numpy-test 

frameworkVersion: ">=1.1.0 <2.0.0"

plugins:
  - serverless-domain-manager
  - serverless-python-requirements
custom:
  pythonRequirements:
    dockerizePip:non-linux

  stage: ${opt:stage, self:provider.stage}
  domains:
    prod: ...
    staging: ...
    dev: ...

当我在上传后尝试测试功能时,serverless invoke -f numpy --log 出现以下错误

    "errorMessage": "Unable to import module 'handler'"
}
--------------------------------------------------------------------
START RequestId: 24584f5c-5145-4694-b21b-7c6e4700f985 Version: $LATEST
Unable to import module 'handler':
Importing the multiarray numpy extension module failed.  Most
likely you are trying to import a failed build of numpy.
If you're working with a numpy git repo, try `git clean -xdf` (removes all
files not under version control).  Otherwise reinstall numpy.

Original error was: cannot import name 'multiarray'

当我直接从 AWS lambda 下载依赖项时,看起来该包是在 Windows 中编译的。

在此处输入图像描述

我已经安装了 Docker,据我所知它工作正常。我以前没有使用过它,所以我尝试使用这个解决方案,而不是在 Docker 中学习很多新命令。

出了什么问题?

标签: numpydockerpython-3.6serverless-frameworkaws-serverless

解决方案


我不确定您的情况到底发生了什么,但如果您想numpy在 Lambda 中使用,请查看Lambda 层和官方 (AWS) 层和。numpyscipy

要使用它,请在 serverless.yml 中的函数中添加一个layers部分

functions:
  myFunction:
    layers:
      - arn:aws:lambda:us-east-1:668099181075:layer:AWSLambda-Python36-SciPy1x:2

您可能需要根据您定位的 AWS 区域更改 ARN。


推荐阅读