AWSメモ > ChaliceでAPI Gateway&Lambda開発 †
インストール †pip install chalice プロジェクト作成 †chalice new-project helloworld && cd helloworld サンプルコード †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 )で行う事ができる { "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 の状態で作成される †回避策はあるかもしれないが。未調査。 Lambda関数のみをデプロイする事はできない †下記URLによると、少なくとも1つの @app.route を含める必要があり、 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. |