【Severless】AWS Chalice ~ 入門編 ~

■ はじめに

https://dk521123.hatenablog.com/entry/2024/05/26/001612

の続き。

AWS Chalice (チャリス) について、取り上げる

目次

【1】AWS Chalice
【2】インストール
【3】コマンド一覧
【4】Hello world
 1)プロジェクト作成
 2)ローカル実行
 3)AWSへのデプロイ
 4)後片付け
【5】S3 bucketのイベントを拾うLambda
 1)プロジェクト作成
 2)修正する

【1】AWS Chalice

* AWSが提供しているサーバーレス アプリケーションを
 作成するためのPython 製フレームワーク

cf. Chalice (チャリス) = 聖杯

https://github.com/aws/chalice
https://aws.amazon.com/jp/builders-flash/202003/chalice-api/
動画
https://aws.amazon.com/jp/blogs/news/webinar-bb-aws-chalice-2019/
https://www.youtube.com/watch?v=lB1mgtjhIvw

【2】インストール

# Python製なので、pipインストール
pip3 install chalice

# 確認
chalice --version

【3】コマンド一覧

Commands Explanations Memo
deploy AWSへのデプロイ chalice deploy --stage staging
delete AWS削除 chalice delete --stage dev
local ローカル実行
new-project プロジェクト作成
url デプロイされた API の URLの確認

【4】Hello world

ハンズオン
https://aws.amazon.com/jp/blogs/startup/event-report-chalice-handson/

1)プロジェクト作成

# chalice new-project [プロジェクト名]
$ chalice new-project helloworld

$ cd helloworld
$ tree -a
.
├── .chalice
│   └── config.json
├── .gitignore
├── app.py
└── requirements.txt

app.py

from chalice import Chalice

app = Chalice(app_name='helloworld')


@app.route('/')
def index():
    return {'hello': 'world'}


# The view function above will return {"hello": "world"}
# whenever you make an HTTP GET request to '/'.
#
# Here are a few more examples:
#
# @app.route('/hello/{name}')
# def hello_name(name):
#    # '/hello/james' -> {"hello": "james"}
#    return {'hello': name}
#
# @app.route('/users', methods=['POST'])
# def create_user():
#     # This is the JSON body the user sent in their POST request.
#     user_as_json = app.current_request.json_body
#     # We'll echo the json body back to the user in a 'user' key.
#     return {'user': user_as_json}
#
# See the README documentation for more examples.
#

2)ローカル実行

$ chalice local
Serving on http://127.0.0.1:8000
Restarting local dev server.
Serving on http://127.0.0.1:8000

ブラウザでアクセスした場合の表示
http://127.0.0.1:8000

{
    "hello": "world"
}

3)AWSへのデプロイ

# $ chalice deploy --profile chalice --stage dev
$ chalice deploy

$ chalice url
https://XXXXXXXXXXX.execute-api.us-west-2.amazonaws.com/api/

$ curl $(chalice url)
{"hello":"world"}

4)後片付け

$ chalice delete

【5】S3 bucketのイベントを拾うLambda

https://aws.github.io/chalice/topics/events.html#s3-events

1)プロジェクト作成

# プロジェクト名は指定せずに、、、
$ chalice new-project
   ___  _  _    _    _     ___  ___  ___
  / __|| || |  /_\  | |   |_ _|/ __|| __|
 | (__ | __ | / _ \ | |__  | || (__ | _|
  \___||_||_|/_/ \_\|____||___|\___||___|


The python serverless microframework for AWS allows
you to quickly create and deploy applications using
Amazon API Gateway and AWS Lambda.

Please enter the project name
[?] Enter the project name: demo-s3-event << ★プロジェクト名を指定
[?] Select your project type: S3 Event Handler << ★「S3 Event Handler」を選択
   REST API
 > S3 Event Handler
   Lambda Functions only
   Legacy REST API Template
   [CDK] Rest API with a DynamoDB table

Your project has been generated in ./demo-s3-event

$ cd demo-s3-event
$ tree -a
.
├── .chalice
│   └── config.json
├── .gitignore
├── app.py
├── chalicelib
│   └── __init__.py
├── requirements-dev.txt
├── requirements.txt
└── tests
    ├── __init__.py
    └── test_app.py

app.py

import os

from chalice import Chalice

app = Chalice(app_name='demo-s3-event')
app.debug = True

# Set the value of APP_BUCKET_NAME in the .chalice/config.json file.
S3_BUCKET = os.environ.get('APP_BUCKET_NAME', '')

@app.on_s3_event(bucket=S3_BUCKET, events=['s3:ObjectCreated:*'])
def s3_handler(event):
    app.log.debug("Received event for bucket: %s, key: %s",
                  event.bucket, event.key)

2)修正する

「# Set the value of APP_BUCKET_NAME in the .chalice/config.json file.」
って言っているので、修正する

https://chalice-fei.readthedocs.io/en/latest/topics/configfile.html#environment-variables
.chalice/config.json (修正前)

{
  "version": "2.0",
  "app_name": "demo-s3-event",
  "stages": {
    "dev": {
      "api_gateway_stage": "api"
    }
  }
}

.chalice/config.json (修正後)

{
  "version": "2.0",
  "app_name": "demo-s3-event",
  "stages": {
    "dev": {
      "api_gateway_stage": "api",
      "environment_variables": {
        "APP_BUCKET_NAME": "your-s3-bucket-dev"
      }
    },
    "stage": {
      "api_gateway_stage": "api",
      "environment_variables": {
        "APP_BUCKET_NAME": "your-s3-bucket-stage"
      }
    },
    "prod": {
      "environment_variables": {
        "APP_BUCKET_NAME": "your-s3-bucket-prod"
      }
    }
  }
}

参考文献

https://www.cloudbuilders.jp/articles/2265/
https://qiita.com/hirai-11/items/e6c8b12dab5728d36684
https://qiita.com/hirai-11/items/3f7c5d53f03b9b0d66ea
https://qiita.com/takeh/items/e52ad1c541a435e2b2e3
https://qiita.com/matsunao722/items/9626969b9636dd232a92
https://dev.classmethod.jp/articles/intro-chalice/

関連記事

Serverless Framework以外のフレームワーク
https://dk521123.hatenablog.com/entry/2024/05/26/001612