如何部署需要使用无服务器框架进行pip安装的AWS Lambda Python脚本。
在上一篇文章中,我写了有关需要安装gem的AWS Lambda的Ruby脚本的文章。
程序大纲
您可以通过插入
插件轻松地做到这一点。
详细程序
无服务器框架服务创建
1 2 3 4 5 6 7 8 9 10 11 12 | $ serverless create --template aws-python3 Serverless: Generating boilerplate... _______ __ | _ .-----.----.--.--.-----.----| .-----.-----.-----. | |___| -__| _| | | -__| _| | -__|__ --|__ --| |____ |_____|__| \___/|_____|__| |__|_____|_____|_____| | | | The Serverless Application Framework | | serverless.com, v2.16.1 -------' Serverless: Successfully generated boilerplate for template: "aws-python3" Serverless: NOTE: Please update the "service" property in serverless.yml with your service name |
将生成三个
文件。
1 2 3 | .gitignore handler.py serverless.yml |
插件安装
安装插件
1 | $ serverless plugin install -n serverless-python-requirements |
以下文件和目录将增加。
1 2 3 | node_modules package.json package-lock.json |
由于
无服务器框架是在Node.js中实现的,因此
源代码
serverless.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | service: sample frameworkVersion: '2' provider: name: aws runtime: python3.8 region: ap-northeast-1 functions: hello: handler: handler.hello plugins: - serverless-python-requirements |
requirements.txt
让我们使用名为
示例库。用于确定日本假期的图书馆。
创建
1 | jpholiday |
让我们使用名为
示例。用于确定日本假期的图书馆。
Python源代码
1 2 3 4 5 6 | import datetime import jpholiday def hello(event, context): holidayName = jpholiday.is_holiday_name(datetime.date(2021, 8, 8)) print(holidayName) # CloudWatch に "山の日" と書き出される |
部署
如果到目前为止已创建
,然后使用
1 | $ serverless deploy -v |
运行
如果在部署后在AWS管理控制台中查看Lambda,则如下所示:
与Ruby不同,似乎该库直接存储在Lambda中而不是Layer中。
2021/01/29附录
如果将设置添加到
在AWS Lambda Python无服务器框架
层上安装pip
链接
- (Ruby版本)在具有Ruby环境的Serverless Framework和AWS Lambda中安装gem