webmaster-kazu.com

テクノロジー・データ分析・実践ログ・その他

Serverless Frameworkテンプレート内にプログラムを追加し更新する

カテゴリ: Node.js

Serverless Frameworkテンプレート内にプログラムを追加し更新してみます。

前回、Serverless Frameworkを用いてテンプレートを作成しPython関数を呼び出すという記事を公開しましたが、今回はServerless Frameworkを用いて作成したテンプレート内のプログラムを追加し更新してみます。

■PC環境

>Windows 10

>npm --version

8.3.1

>node --version

v16.14.0

>nodeserverless --version

Framework Core: 3.19.0

Plugin: 6.2.2

SDK: 4.3.2

>aws --version

aws-cli/2.5.6 Python/3.9.11 Windows/10 exe/AMD64 prompt/off

■プロジェクトディレクトリを作成する

前回、Serverless Frameworkを用いて「C:\Users\user_\project_test(フォルダパス)」内に「project_test」ディレクトリを作成し、その中に「.gitignore」、「handler.py」、「serverless.yml」という3つのファイルが生成されましたが、プログラムを追加してみますので、「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

}

"""

コードエディタで開くと上記のコードが表示されます。

■コード(変更後)

import json

def hello(event, context):

a = 10

b = 5

return a+b

表示後、コードを上記のように変更します。def文を用いてhelloという関数を定義し、関数を呼び出した時に実行される処理として、a変数とb変数に格納した数値を算術演算子"+"(プラス)を用いて加算し、加算した結果をreturnとして返すようにします。

コードを記述後、保存します。

■追加したプログラムを更新する

保存後、追加(変更)したプログラムを更新するために、Windows10のコマンドプロンプトを起動します。

C:\Users\user_>cd project_test

起動後、上記のコマンドを入力し、Enterキーを入力します。cdコマンドで作成した「project_test」ディレクトリに移動します。

C:\Users\user_\project_test>cd project_test

移動後、上記のコマンドを入力し、Enterキーを入力します。さらにServerless Frameworkを用いて作成した「project_test」ディレクトリに移動します。

C:\Users\user_\project_test\project_test>serverless deploy function -f hello

移動後、上記のコマンドを入力し、Enterキーを入力します。「deploy function -f」コマンドで、def文を用いて定義したhello関数をデプロイします。

Deploying function hello to stage dev (us-east-1)

✔ Function code deployed (2s)

Configuration did not change. Configuration update skipped. (2s)

Enterキーを押すと、上記のメッセージが出力されます。「Function code deployed」にチェックが入っているので、これでデプロイは完了となります。

■関数を呼び出す

完了後、検証のために、プログラムを実行し、関数を呼び出してみます。

C:\Users\user_\project_test\project_test>serverless invoke -f hello -l

関数を呼び出すために、コマンドプロンプト上で、上記のコマンドを入力し、Enterキーを入力します。「invoke」コマンドで関数を呼び出します。

15

START

END RequestId: ****----*******

END Duration: 1.10 ms (init: 110.79 ms) Memory Used: 36 MB

Enterキーを押すと、def文を用いてhelloという関数を定義しましたが、定義した関数を呼び出しreturnを返させることができました。