AWSメモ >

ChaliceでAPI Gateway&Lambda開発

インストール

pip install chalice

プロジェクト作成

chalice new-project helloworld && cd helloworld

サンプルコード

Flask でアプリケーション作成をした事があれば、スムーズに利用する事ができると思う。
※デコレータ等は、ほぼ Flask のインターフェースと同じ。

app.py

from chalice import Chalice, Response

app = Chalice(app_name='helloworld')

@app.route('/sample1', methods=['GET', 'POST', 'PUT', 'DELETE'])
def sample1():

    request = app.current_request
    headers = request.headers

    try:
      #if hasattr(request, 'json_body'):
      body = request.json_body
    except:
      body = None

    ## debug ##
    if headers:
      for k in headers:
        print ( k + " = " + headers[k] )
    if body:
      for key in body:
        print ( key + " = " + body[key] )
    ###########

    response = { 
      "method": request.method,
      "json_body": body
    }   
    return { 'response': response }

@app.route('/sample2/{key}', methods=['GET', 'POST', 'PUT', 'DELETE'])
def sample2(key):

    request = app.current_request
    headers = request.headers

    try:
      #if hasattr(request, 'json_body'):
      body = request.json_body
    except:
      body = None

    ## debug ##
    if key:
      print ( "key is " + key )
    if headers:
      for k in headers:
        print ( k + " = " + headers[k] )
    #body = json.loads(request.json_body)
    if body:
      for key in body:
        print ( key + " = " + body[key] )
    ###########

    response = { 
      "method": request.method,
      "json_body": body
    }

@app.route('/error1')
def error1():
    raise BadRequestError("This is a bad request")

@app.route('/error2')
def error2():
    error = {'code': 'ERROR2', 'message': "Error message!" }
    return Response(body=error,
                    status_code=400,
                    headers={'Content-Type': 'text/plain'})

動作確認

ローカル起動

chalice local

確認リクエスト送信

curl -XPOST -H 'Content-type: application/json' --data '{"param1":"ABC"}' http://localhost:8000/sample2/123

デプロイ

chalice deploy

削除

chalice delete --stage dev

設定ファイル

諸々の設定を コンフィグファイル( ./chalice/config.json )で行う事ができる
http://chalice.readthedocs.io/en/latest/topics/configfile.html

{
  "version": "2.0",
  "app_name": "app",
  "stages": {
    "dev": {
      "autogen_policy": true,
      "api_gateway_stage": "dev"
    },
    "beta": {
      "autogen_policy": false,
      "iam_policy_file": "beta-app-policy.json"
    },
    "prod": {
      "manage_iam_role": false,
      "iam_role_arn": "arn:aws:iam::...:role/prod-role"
    }
  }
}

制限

API Gateway は「Lambdaプロキシ統合の使用」が ON の状態で作成される

回避策はあるかもしれないが。未調査。
API Gateway に引っ付く Lambda しか作成しない場合は特に問題ないが、
そうでない場合は、リクエスト、レスポンスの扱いに注意が必要。
※Lambdaプロキシ統合の使用を前提に呼び出す必要がある。
※というか、現時点(2018/1)ではChalice では API Gateway に引っ付かない Lambda の作成はできないらしい。(後述)

Lambda関数のみをデプロイする事はできない

下記URLによると、少なくとも1つの @app.route を含める必要があり、
API Gateway 無しで Lambda をデプロイする事はできないらしい。

http://chalice.readthedocs.io/en/latest/topics/purelambda.html

Limitations:

You must provide at least 1 @app.route decorator. It is not possible to deploy only lambda functions without an API Gateway API.


トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2018-01-25 (木) 02:44:02 (2282d)