Deploy Python3 function with Serverless Framework on AWS Lambda

Introduction

--This article is Python Part 3 Advent Calendar 2019 is the 16th day. --This is a memo until you deploy and publish a Python3 function with Serverless Framework on AWS Lambda.

Premise

--The npm command can be used --There is an IAM user for serverless framework --You can refer to the official this area (Administrator Access is recommended). --Docker can be used

Serverless Framework installation and configuration

Installation is one shot of npm install.

$ npm install serverless

Make sure the path is in --version.

$ serverless --version
Framework Core: 1.59.3
Plugin: 3.2.5
SDK: 2.2.1
Components Core: 1.1.2
Components CLI: 1.4.0

Set the IAM account for Serverless Framewrok created in advance with serverless config credentials.

serverless config credentials --provider aws --key foo --secret bar

This completes the preparations.

Template generation and deploy

Generate a template project for Python3.

serverless create --template aws-python3 --name aws-lambda-hello-python --path aws-lambda-hello-python

The following files are actually generated.

$ cd aws-lambda-hello-python

$ tree
.
├── handler.py
└── serverless.yml

0 directories, 2 files

In the above command, the main method is not generated, but this time I wanted to make it work locally, so I added it.

handler.py



import json


def hello(event, context):
    body = {
        "message": "Go Serverless v1.0! Your function executed successfully!",
        "input": event
    }

    response = {
        "statusCode": 200,
        "body": json.dumps(body)
    }

    return response

    # Use this code if you don't use the http event with the LAMBDA-PROXY
    # integration
    """
    return {
        "message": "Go Serverless v1.0! Your function executed successfully!",
        "event": event
    }
    """

if __name__  == "__main__":
    print(json.dumps(hello("","")))

There are a lot of comments, but the minimum required is: (Since you haven't specified a region, it will be deployed to the default us-east-1)

serverless.yml


service: aws-lambda-hello-python

provider:
  name: aws
  runtime: python3.8

functions:
  hello:
    handler: handler.hello

Let's move it a little with Local.

$ pyenv local 3.8.0
$ python3 handler.py
{"statusCode": 200, "body": "{\"message\": \"Go Serverless v1.0! Your function executed successfully!\", \"input\": \"\"}"}

It worked. Now, let's deploy and check the operation.

$ serverless deploy -v
(Message omitted)

$ serverless invoke -f hello
{
    "statusCode": 200,
    "body": "{\"message\": \"Go Serverless v1.0! Your function executed successfully!\", \"input\": {}}"
}

It seems that it was able to deploy properly.

Use of external libraries

--I would like to be able to use an external library. ――I would like to introduce numpy, but the native library needs to be built for each environment, and it is a little troublesome when using it with Lambda normally, but using Serverless Framework makes it relatively easy.

Make the venv environment available, install numpy and freeze it.

$ python3 -m venv .venv
$ .venv/bin/pip install numpy
$ .venv/bin/pip freeze > requirements.txt

Add the process that uses numpy appropriately. (The mean will change).

handler.py


import json
import numpy as np


def hello(event, context):
    arr = range(1, 100+1)
    mean = np.mean(arr)

    body = {
        "message": "Go Serverless v1.0! Your function executed successfully!",
        "input": event,
        "mean" : mean
    }

    response = {
        "statusCode": 200,
        "body": json.dumps(body)
    }

    return response

    # Use this code if you don't use the http event with the LAMBDA-PROXY
    # integration
    """
    return {
        "message": "Go Serverless v1.0! Your function executed successfully!",
        "event": event
    }
    """

if __name__  == "__main__":
    print(json.dumps(hello("","")))

When executed locally, it looks like this.

$ .venv/bin/python3 handler.py
{"statusCode": 200, "body": "{\"message\": \"Go Serverless v1.0! Your function executed successfully!\", \"input\": \"\", \"mean\": 50.5}"}

Install a plugin that allows serverless to use requirements.

npm install serverless-python-requirements

Add to serverless.yml (add plugins and below)

service: aws-lambda-hello-python

provider:
  name: aws
  runtime: python3.8

functions:
  hello:
    handler: handler.hello

plugins:
  - serverless-python-requirements

custom:
  pythonRequirements:
    dockerizePip: true

package:
  include:
    - handler.py
  exclude:
    - '**'

Try deploying (docker will run a numpy build and deploy it)

$ serverless deploy -v

Let's check the operation.

$ serverless invoke -f hello
{
    "statusCode": 200,
    "body": "{\"message\": \"Go Serverless v1.0! Your function executed successfully!\", \"input\": {}, \"mean\": 50.5}"
}

Numpy is working properly! Let's have a fun Python & Serverless life!

Recommended Posts

Deploy Python3 function with Serverless Framework on AWS Lambda
Create Python version Lambda function (+ Lambda Layer) with Serverless Framework
Touch AWS with Serverless Framework and Python
Install pip in Serverless Framework and AWS Lambda with Python environment
Deploy Django serverless with Lambda
I want to AWS Lambda with Python on Mac!
Write AWS Lambda function in Python
Run Python on Schedule on AWS Lambda
Notify HipChat with AWS Lambda (Python)
[AWS] Using ini files with Lambda [Python]
Serverless scraping on a regular basis with AWS lambda + scrapy Part 1
[Python] Run Headless Chrome on AWS Lambda
Connect to s3 with AWS Lambda Python
Python + Selenium + Headless Chromium with aws lambda
Periodically run a python program on AWS Lambda
Use additional Python packages with Serverless Framework (v1.x)
Regular serverless scraping with AWS lambda + scrapy Part 1.8
Serverless scraping using selenium with [AWS Lambda] -Part 1-
LINE BOT with Python + AWS Lambda + API Gateway
Lambda function deploy best practices with CircleCI + Lamvery
AWS CDK with Python
[GCP] [Python] Deploy API serverless with Google Cloud Functions!
Dynamic HTML pages made with AWS Lambda and Python
Check types_map when using mimetypes on AWS Lambda (Python)
Execute python3 system with PHP exec () on AWS EC2
Support for Python 2.7 runtime on AWS Lambda (as of 2020.1)
Create a Layer for AWS Lambda Python with Docker
Make ordinary tweets fleet-like with AWS Lambda and Python
Operate TwitterBot with Lambda, Python
[Python] Scraping in AWS Lambda
Python compilation with pyqt deploy
AWS Lambda with PyTorch [Lambda import]
Effortlessly with Serverless Python Requirements
Posted as an attachment to Slack on AWS Lambda (Python)
[AWS] Try adding Python library to Layer with SAM + Lambda (Python)
Post images of Papillon regularly on Python + AWS Lambda + Slack
Create API with Python, lambda, API Gateway quickly using AWS SAM
[Python] Allow pip3 packages to be imported on AWS Lambda
Site monitoring and alert notification with AWS Lambda + Python + Slack
Securely deploy your Lambda function using Python built with the same options as Amazon Linux
[Python] Convert CSV file uploaded to S3 to JSON file with AWS Lambda
Summary if using AWS Lambda (Python)
Get started with the Python framework Django on Mac OS X
[AWS] Create API with API Gateway + Lambda
Build a local development environment for Lambda + Python using Serverless Framework
Build a Flask / Bottle-like web application on AWS Lambda with Chalice
Text extraction with AWS Textract (Python3.6)
Face detection with Lambda (Python) + Rekognition
[Python 3.8 ~] How to define a recursive function smartly with a lambda expression
xgboost (python) on EC2 Spot instance environment prepared by AWS Lambda
Things to note when running Python on EC2 from AWS Lambda
Manipulating kintone data with Python & C Data ODBC Driver from AWS Lambda
Best practice for logging in JSON format on AWS Lambda / Python
[Python] Make the function a lambda function
Using Lambda with AWS Amplify with Go
Run python3 Django1.9 with mod_wsgi (deploy)
Notes on using rstrip with python.
If you are having trouble with timeouts when implementing Slack's SlashCommand in Python on AWS Lambda
Let's make a web chat using WebSocket with AWS serverless (Python)!
Getting started with Python 3.8 on Windows
Use PostgreSQL with Lambda (Python + psycopg2)