1
2

More than 3 years have passed since last update.

Chalice入門

Last updated at Posted at 2021-07-25

Chaliceとは?

ChaliceはAmazon公式のPythonライブラリで、AWS製のサーバーレスフレームワークツールであり、boto3, botocoreの開発者による継続的なメンテナンスがされています。
コマンドでAWS LambdaとAPI Gatewayの設定を済ませてくれます。

Chaliceの導入

Chaliceのインストール

pipコマンドを利用してPythonパッケージのChaliceをインストールします。

$ pip install chalice

プロジェクトの作成

$ chalice new-project {任意のプロジェクト名}
$ cd {任意のプロジェクト名}

デプロイ

app.pyの中身を確認

$ cat app.py
app.py

from chalice import Chalice

app = Chalice(app_name='{任意のプロジェクト名}')


@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.

デプロイ

$ chalice deploy

Creating deployment package.
Creating IAM role: wheatclinic-backend-dev
Creating lambda function: wheatclinic-backend-dev
Creating Rest API
Resources deployed:
  - Lambda ARN: arn:aws:lambda:ap-northeast-1:xxxxxxxxxxxxxxxxxxxx:function:wheatclinic-backend-dev
  - Rest API URL: https://xxxxxxxxxxxxxxxxxxxx.ap-northeast-1.amazonaws.com/api/

URLが返ってくるのでアクセスすると、以下のような画面が表示される.

スクリーンショット 2021-07-25 15.01.23.png

ローカル起動

以下のコマンドを実行するとローカルでサービス起動できます.

$ chalice local

Blueprintの導入

Blueprintとは、アプリケーションの機能を分割して実装するためのものです.
それに伴うディレクトリーとpythonファイルを作成します。

mkdir demo
touch __init__.py
touch demo.py

demo.pyに分割する機能を書いていきます。

demo.py
from chalice import Blueprint

demo_routes = Blueprint(__name__)

@demo_routes.route('/foo')
def foo():
    return {'foo': 'bar'}

app.pyに以下の記述を追記します。

app.py

app.register_blueprint(demo_routes)

ファイル構造としては以下の通りです。

$ tree -a

├── app.py
├── demo
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-38.pyc
│   │   └── demo.cpython-38.pyc
│   └── demo.py
├── requirements.txt

ローカル起動させれpostmanでアクセスすると以下のようになります。
スクリーンショット 2021-07-25 16.24.14.png

参考にさせていただいた記事

【Chaliceに入門してみた】LambdaとAPI Gatewayを手動で構築して消耗していた過去の私へ | DevelopersIO
AWSChaliceを使用してサーバーレスアプリケーションを構築する方法
Documentation — AWS Chalice
AWS Chaliceで爆速でREST APIを作ってみる | It works for me
[AWS Black Belt Online Seminar] Dive deep into AWS Chalice 資料及び QA 公開 | Amazon Web Services ブログ
【Chalice】AWS Lambdaで簡単サーバレス環境構築 | トモテク
Chalice — AWS Chalice

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2