Summary of studying Python to use AWS Lambda

AWS Lambda Python !!!

Weekend update, Yoshida. AWS Lambda uses Python because node async is too over-technology for me (I didn't have the option of Java). I've written AWS Lambda functions so much, and I've figured out how to use them, so I've summarized the ones I use often.


import Module to use

import module name

Import in the format of. There are various external modules in Python that can be used by importing them. I think that boto3 is the most used for AWS Lambda. boto is a Python version of the SDK for working with AWS APIs.

sample


import boto3
ec2 = boto3.resource('ec2')

Module name. Method ('give argument')

You should be able to use it if you use it like this. In the above example, by storing it in the variable [ec2], the ec2 method can be used in ec2.hogehoge.


variable

Using variables in Python

variable


variable= 'hogehoge'

Use like. There is no need to declare types like Java.

Since Python doesn't have constants, it seems that variables in all uppercase letters are constants.


Array

List type variables are used as follows

Array


array = ["hoge","fuga","bar"]

Array uses [] Since the elements of the array are stored from 0, to access the element "hoge" in the above example

sample


array = ["hoge","fuga","bar"]
sample = array[0]

If you do like this, the element number 0 (hoge) of array will be stored in sample.

__Adding elements to the array __ You can add an element to the end of an array (list) by using .append

array = ["hoge","fuga","bar"]
array.append("hogeeeee")

By doing this, the array will be

array = ["hoge","fuga","bar","hogeeeee"]

It will be.

__ Remove elements from array __ You can delete the elements of the array (list) by using .pop. Deletes the specified element with .pop (element number). If .pop () and element number are not specified, the end will be deleted. .pop returns the deleted element

array = ["hoge","fuga","bar","hogeeeee"]
var = array.pop()

array = ["hoge","fuga","bar"] var = "hogeeeee"

It will be like this.


Dictionary type array

__ I want to keep a set of keys and values as an array and specify the keys to set the values __ The dictionary type is used in such cases.

dic = {"id":"i-hogehoge","type":"4xlarge"}

I use it like this. Unlike the list type, it can be used as a dictionary type by enclosing it in {}.

Fetch the value for the key

dic = {"id":"i-hogehoge","type":"4xlarge"}
dic["id"]

i-hogehoge

Get the value for the key with __dictionary array name [key name] __.

Use the __len () __ function to get the total prime number of a dictionary array.

dic = {"id":"i-hogehoge","type":"4xlarge"}
dic_num = len(dic)

Convenient when turning around with a for statement __ By the way, all dictionaries, lists and tuples are okay with len __

__ Add / Remove Elements __

add to

dic = {"id":"i-hogehoge","type":"4xlarge"}
dic["AZ"] = "a"
dic["type"] = "xlarge" 

dic = {"id":"i-hogehoge","type":"xlarge","AZ":"a"}

I will add it like this. Note that if you specify a key that does not exist, you will create a new one, If you specify a key that already exists, it will be overwritten.

Delete Delete with .pop (key name).

dic = {"id":"i-hogehoge","type":"4xlarge"}
dic.pop('type')

function

When using a function in Python, use def to define the function.

def


def sample1(content1, content2):
	print(content1)
	print(content2)

It looks like this. Define the arguments to pass to the function in () in de. You can specify more than one by separating them. Use the function as a function name (argument 1, argument 2). You can also return the result of the processing in the function. To return the result, use the return statement to return the processing result of the function to the caller.

sample


def lambda_handler(event, context):
	kansu_kekka = kansu1(hoge, hoge)
	
	print(kansu_kekka)
	
	
	
	
def kansu1(hikisu1, hikisu2):
	moji_1 = hikisu1
	moji_2 = hikisu2
	kekka = moji_1 + moji_2
	
	return kekka

hogehoge

It is an image like. __ If you want to return multiple values, you can use list tuple dictionary type. __

kekka_array = [hoge, bar, fuga]
retrun kekka_array

Something like this. Dictionaries and tuples have the same feeling


for statement

I personally use AWS Lambda, and as a usage of for, it feels like each that turns the elements of the list. About the method

array = ["hoge","fuga","bar","hogeeeee"]
count = len(array)

for i in range(0, count):
	<Processing you want to repeat>

if statement

type = 't2.micro'

if type == 'm4.4xlarge':
	print("NOOOOOOOOOOOO!!!!!")
elif type == 'm4.xlarge': 
	print("OK")
else:
	print(type)
	

The comparison operator looks like this

operator meaning
== equal
!= Not equal
> large
>= Greater or equal
< small
<= Small or equal

Function: lambda_handler (event, context)

Let's move on from the basics of Python to AWS Lambda. This sentence is the most mysterious thing when I first touched AWS Lambda (Python2.7).

When AWS Lambda runs, AWS Lambda executes this function in the specified program. You can change the name of this function, but if you do, you'll have to rename the execution function in the AWS Lambda console. Unless you have a specific reason, you should use this name by default. The event specified in the argument stores the information passed to AWS Lambda when the AWS Lambda function is executed in JSON format.

When you run AWS Lambda in an event driven manner, some event information is stored in this event, so you can get the information you want by digging around this JSON.

You shouldn't worry about context for the time being. You can get useful information as described in Context Object (Python), I'm confused. Keep it in the corner of your head until you will need it. You can check it when you use it. Someday such a time will come.


I wrote it, but if you know this area and how to go crazy with JSON, I think that you can take the first step of AWS Lambda.

I wrote about JSON in this article before, so please refer to it.

I have a strong personal memo feeling, so if I brush up a little more, I'll write it on the engineer blog.

Recommended Posts

Summary of studying Python to use AWS Lambda
[Python2.7] Summary of how to use unittest
Summary of how to use Python list
[Python2.7] Summary of how to use subprocess
Summary of how to write AWS Lambda
Summary of how to use MNIST in Python
How to use Python lambda
Summary if using AWS Lambda (Python)
Summary of how to use pyenv-virtualenv
Summary of points I was addicted to running Selenium on AWS Lambda (python)
Summary of how to use csvkit
[Python] Summary of how to use split and join functions
Connect to s3 with AWS Lambda Python
[Road to intermediate Python] Use lambda expressions
[Question] How to use plot_surface of python
Basic grammar of Python3 system (how to use functions, closures, lambda functions)
ImportError when trying to use gcloud package with AWS Lambda Python version
[Python] How to use two types of type ()
Summary of how to import files in Python 3
Summary of Python arguments
[Introduction to Python] Basic usage of lambda expressions
Use AWS lambda to scrape the news and notify LINE of updates on a regular basis [python]
Summary of tools needed to analyze data in Python
I tried to summarize how to use matplotlib of python
How to use Python Kivy ① ~ Basics of Kv Language ~
Support for Python 2.7 runtime on AWS Lambda (as of 2020.1)
I want to AWS Lambda with Python on Mac!
Re: Python lambda is useless ^ H ^ H ^ H ^ H ^ H Difficult to use
Summary of Python3 list operations
python3: How to use bottle (2)
[Python] Scraping in AWS Lambda
[Python] How to use list 1
How to use Python argparse
Python: How to use pydub
[Python] How to use input ()
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Python bytes
I'm thinking of studying Python
[AWS] Try adding Python library to Layer with SAM + Lambda (Python)
Comparison of how to use higher-order functions in Python 2 and 3
Post images of Papillon regularly on Python + AWS Lambda + Slack
[AWS Lambda] Use any container Image in Python very simply
[Python] Allow pip3 packages to be imported on AWS Lambda
How to get the information of organizations, Cost Explorer of another AWS account with Lambda (python)
Python: How to use async with
[Python] How to use Pandas Series
How to use Requests (Python Library)
A brief summary of Python collections
How to use SQLite in Python
[Lambda] [Python] Post to Twitter from Lambda!
Write AWS Lambda function in Python
Proper use of Python visualization packages
Run Python on Schedule on AWS Lambda
[Python Queue] Convenient use of Deque
Tweet WakaTime Summary using AWS Lambda
[Introduction to Python] Let's use pandas
[Python] How to use list 3 Added
How to use Mysql in python
How to use OpenPose's Python API