AWS CDK를 사용하여 API 프런트 Lambda 함수 배포
10573 단어 cloudpythonmachinelearningaws
이 패턴을 사용하여 가능한 것은 무엇입니까?
1) 함수에 데이터를 전달하고 기계 학습 예측을 다시 얻습니다.
2)
S3에 저장된 파일을 요청하고 보안 링크를 다시 가져옵니다.3) 함수에 매개변수를 보내고 복잡한 계산을 다시 가져옵니다.
4) 데이터베이스 검색.
등...
Github repository can be found here.
CDK 초기화 및 배포
CDK 설정 및 환경 부트스트래핑은 다루지 않겠습니다. 해당 정보를 찾을 수 있습니다here..
CDK를 설정했으면 프로젝트를 설정해야 합니다.
mkdir CDK_Lambda_API && cd CDK_Lambda_API cdk init --language python source .venv/bin/activate aws-cdk.aws-lambda-python-alpha를 추가합니다. pip install -r requirements.txt && pip install -r requirements-dev.txt이제 빈 스택을 AWS에 배포합니다.
cdk deploy 스택 설계
이 스택은 도커 컨테이너를 사용하여 모든 추가 라이브러리로 함수를 빌드하기 위해
aws-lambda-python-alpha를 사용하여 람다 함수를 배포합니다. 실행하기 전에 Docker가 설치되어 있고 데몬이 실행 중인지 확인하십시오cdk deploy.# lambda_api_stack.py
from aws_cdk import Stack
from aws_cdk import aws_apigateway as apigw
from aws_cdk import aws_lambda as _lambda
from aws_cdk import aws_lambda_python_alpha as _lambda_python
from constructs import Construct
class LambdaModelPredictionsStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
# in __init__ I like to initialize the infrastructure I will be creating
self.prediction_lambda = None
self.gateway = None
# Additional useful infrastructure might include an S3 bucket,
# an EFS store, SQS queue, etc.
self.build_infrastructure()
def build_infrastructure(self):
# For convenience, consolidate infrastructure construction
self.build_lambda()
self.build_gateway()
def build_lambda(self):
self.prediction_lambda = _lambda_python.PythonFunction(
scope=self,
id="PredictionLambda",
# entry points to the directory
entry="lambda_funcs/APILambda",
# index is the file name
index="API_lambda.py",
# handler is the function entry point name in the lambda.py file
handler="handler",
runtime=_lambda.Runtime.PYTHON_3_9,
# name of function on AWS
function_name="ExampleAPILambda",
)
def build_gateway(self):
# This will attach an API gateway as a trigger to our
# lambda function above. The return of the handler function also
# gets routed back to the API gateway.
self.gateway = apigw.LambdaRestApi(
self, "Endpoint", handler=self.prediction_lambda
)
최소 작동 Lambda 함수
API 게이트웨이가 예상하는 응답 형식의 예here를 볼 수 있습니다.
# lambda_funcs/APILambda/API_lambda.py
from logging import getLogger
logger = getLogger()
logger.setLevel(level="DEBUG")
def handler(event, context):
logger.debug(msg=f"Initial event: {event}")
response = {
"isBase64Encoded": False,
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*",
},
"body": f"Nice! You said {event['queryStringParameters']['q']}",
}
return response
이제 할 수 있습니다
cdk deploy . Lambda 함수는 도커를 사용하여 빌드되고 부트스트랩된 ECR 리포지토리에 업로드됩니다. 프로젝트가 빌드되면 CloudFormation 템플릿을 합성하고 인프라 배포를 시작합니다. AWS CloudFormation에서 스택 배포를 볼 수 있습니다. 인프라가 상대적으로 단순하기 때문에 신속해야 합니다.프로세스가 완료되면 CDK는 API 게이트웨이의 끝점 URL을 출력합니다.

API 게이트웨이 쿼리
API 게이트웨이를 쿼리하고 람다 함수에서 다시 응답을 받으려면
requests 또는 Postman를 사용하여 get 요청을 보내십시오.
Reference
이 문제에 관하여(AWS CDK를 사용하여 API 프런트 Lambda 함수 배포), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/wesleycheek/deploy-an-api-fronted-lambda-function-using-aws-cdk-2nch텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)