Since there are many cases of TypeScript, a memorandum when I tried it with Python.
--A sample that exposes Lambda processing of Python implementation via API Gateway.
--TypeScript comparison
--Add the dependent library to setup.py
(unlike npm install --save
, write it directly in the file).
--Since there are no build steps, the basic operation proceeds quickly (on the other hand, the weakness of type checking is a disadvantage).
--Encountered the phenomenon that .gitignore
is not included in the repository generated by cdk init
. Add a separate file based on the following (it does not seem to occur when language = typescript
).
- https://github.com/aws/aws-cdk/blob/m1aster/packages/aws-cdk/lib/init-templates/app/python/.gitignore
--General
――Since the code completion function based on TypeScript type information is powerful, I don't feel a strong reason to write in Python even if I lose it. On the other hand, it may be advantageous if the implementation code such as Lambda is also implemented in Python and the source is managed in a unified language with Infra (CDK).
The procedure used to check the operation.
$ npm install -g aws-cdk
$ cdk --version
1.19.0 (build 5597bbe)
Initialize the application with cdk-init
. Also, enable virtualenv
with the source
command.
$ mkdir lambda-sample && cd $_
$ cdk init --language=python
$ source .env/bin/activate
setup.py
Dependent library definitions (by default, only ʻaws-cdk.core exists, so add ʻaws-lambda
and ʻaws-apigateway`).
...
install_requires=[
"aws-cdk.core",
"aws-cdk.aws-lambda",
"aws-cdk.aws-apigateway",
],
...
Install dependent libraries based on definition.
$ pip install -r requirements.txt
Script implementation.
$ mkdir lambda
$ touch lambda/handler.py
lambdahandler.py
import json
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def main(event, context):
logger.info(json.dumps(event))
return {
'statusCode': 200,
'body': 'Hello World'
}
lamba_sample/lambda_sample.py
Added Lambda and API Gateway deployment definitions to Stack.
from aws_cdk import (
aws_lambda,
aws_apigateway,
core
)
class LambdaSampleStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
handler = aws_lambda.Function(
self, "backend",
runtime=aws_lambda.Runtime.PYTHON_3_7,
handler="handler.main",
code=aws_lambda.AssetCode(path="./lambda"))
api = aws_apigateway.LambdaRestApi(self, "SampleLambda", handler=handler)
Deploy the defined stack. If you call the API Gateway Endpoint that is output in the ʻOutputs` field, the Lamba output result will be returned.
$ cdk deploy
...
Outputs:
lambda-sample.SampleLambdaEndpoint9FAA5D96 = https://4rtjc3pjfh.execute-api.ap-northeast-1.amazonaws.com/prod/
$ curl https://4rtjc3pjfh.execute-api.ap-northeast-1.amazonaws.com/prod/
Hello World
Recommended Posts