Skip to content

docs(tutorial): extract code examples #1137

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 16 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,11 @@ changelog:

mypy:
poetry run mypy --pretty aws_lambda_powertools

format-examples:
poetry run isort docs/examples
poetry run black docs/examples/*/*.py

lint-examples:
poetry run python3 -m py_compile docs/examples/*/*.py
cfn-lint docs/examples/*/*.yml
10 changes: 10 additions & 0 deletions docs/examples/tutorial/add_route_hello_by_name.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import json


def hello_name(name):
return {"statusCode": 200, "body": json.dumps({"message": f"hello {name}!"})}


def lambda_handler(event, context):
name = event["pathParameters"]["name"]
return hello_name(name)
36 changes: 36 additions & 0 deletions docs/examples/tutorial/add_route_temaplate.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Sample SAM Template for powertools-quickstart
Globals:
Function:
Timeout: 3
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.9
Events:
HelloWorld:
Type: Api
Properties:
Path: /hello
Method: get

HelloWorldByNameFunctionName:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: hello_by_name.lambda_handler
Runtime: python3.9
Events:
HelloWorldName:
Type: Api
Properties:
Path: /hello/{name}
Method: get
Outputs:
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
9 changes: 9 additions & 0 deletions docs/examples/tutorial/code_example_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import json


def hello():
return {"statusCode": 200, "body": json.dumps({"message": "hello unknown!"})}


def lambda_handler(event, context):
return hello()
25 changes: 25 additions & 0 deletions docs/examples/tutorial/code_example_template.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Sample SAM Template for powertools-quickstart
Globals:
Function:
Timeout: 3
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.9
Architectures:
- x86_64
Events:
HelloWorld:
Type: Api
Properties:
Path: /hello
Method: get
Outputs:
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
71 changes: 71 additions & 0 deletions docs/examples/tutorial/create_metrics_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import os

import boto3

from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.logging import correlation_paths

cold_start = True
metric_namespace = "MyApp"

logger = Logger(service="APP")
tracer = Tracer(service="APP")
metrics = boto3.client("cloudwatch")
app = APIGatewayRestResolver()


@tracer.capture_method
def add_greeting_metric(service: str = "APP"):
function_name = os.getenv("AWS_LAMBDA_FUNCTION_NAME", "undefined")
service_dimension = {"Name": "service", "Value": service}
function_dimension = {"Name": "function_name", "Value": function_name}
is_cold_start = True

global cold_start
if cold_start:
cold_start = False
else:
is_cold_start = False

return metrics.put_metric_data(
MetricData=[
{
"MetricName": "SuccessfulGreetings",
"Dimensions": [service_dimension],
"Unit": "Count",
"Value": 1,
},
{
"MetricName": "ColdStart",
"Dimensions": [service_dimension, function_dimension],
"Unit": "Count",
"Value": int(is_cold_start),
},
],
Namespace=metric_namespace,
)


@app.get("/hello/<name>")
@tracer.capture_method
def hello_name(name):
tracer.put_annotation(key="User", value=name)
logger.info(f"Request from {name} received")
add_greeting_metric()
return {"message": f"hello {name}!"}


@app.get("/hello")
@tracer.capture_method
def hello():
tracer.put_annotation(key="User", value="unknown")
logger.info("Request from unknown received")
add_greeting_metric()
return {"message": "hello unknown!"}


@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST, log_event=True)
@tracer.capture_lambda_handler
def lambda_handler(event, context):
return app.resolve(event, context)
31 changes: 31 additions & 0 deletions docs/examples/tutorial/create_metrics_template.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Sample SAM Template for powertools-quickstart
Globals:
Function:
Timeout: 3
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.9
Tracing: Active
Events:
HelloWorld:
Type: Api
Properties:
Path: /hello
Method: get
HelloWorldName:
Type: Api
Properties:
Path: /hello/{name}
Method: get
Policies:
- CloudWatchPutMetricPolicy: {}
Outputs:
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
37 changes: 37 additions & 0 deletions docs/examples/tutorial/create_own_router_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import json


def hello_name(event, **kargs):
username = event["pathParameters"]["name"]
return {"statusCode": 200, "body": json.dumps({"message": f"hello {username}!"})}


def hello(**kargs):
return {"statusCode": 200, "body": json.dumps({"message": "hello unknown!"})}


class Router:
def __init__(self):
self.routes = {}

def set(self, path, method, handler):
self.routes[f"{path}-{method}"] = handler

def get(self, path, method):
try:
route = self.routes[f"{path}-{method}"]
except KeyError:
raise RuntimeError(f"Cannot route request to the correct method. path={path}, method={method}")
return route


router = Router()
router.set(path="/hello", method="GET", handler=hello)
router.set(path="/hello/{name}", method="GET", handler=hello_name)


def lambda_handler(event, context):
path = event["resource"]
http_method = event["httpMethod"]
method = router.get(path=path, method=http_method)
return method(event=event)
28 changes: 28 additions & 0 deletions docs/examples/tutorial/create_own_router_template.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Sample SAM Template for powertools-quickstart
Globals:
Function:
Timeout: 3
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.9
Events:
HelloWorld:
Type: Api
Properties:
Path: /hello
Method: get
HelloWorldName:
Type: Api
Properties:
Path: /hello/{name}
Method: get
Outputs:
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
47 changes: 47 additions & 0 deletions docs/examples/tutorial/enrich_generate_traces_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from aws_xray_sdk.core import patch_all, xray_recorder

from aws_lambda_powertools import Logger
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.logging import correlation_paths

logger = Logger(service="APP")

app = APIGatewayRestResolver()
cold_start = True
patch_all()


@app.get("/hello/<name>")
@xray_recorder.capture("hello_name")
def hello_name(name):
subsegment = xray_recorder.current_subsegment()
subsegment.put_annotation(key="User", value=name)
logger.info(f"Request from {name} received")
return {"message": f"hello {name}!"}


@app.get("/hello")
@xray_recorder.capture("hello")
def hello():
subsegment = xray_recorder.current_subsegment()
subsegment.put_annotation(key="User", value="unknown")
logger.info("Request from unknown received")
return {"message": "hello unknown!"}


@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST, log_event=True)
@xray_recorder.capture("handler")
def lambda_handler(event, context):
global cold_start

subsegment = xray_recorder.current_subsegment()
if cold_start:
subsegment.put_annotation(key="ColdStart", value=cold_start)
cold_start = False
else:
subsegment.put_annotation(key="ColdStart", value=cold_start)

result = app.resolve(event, context)
subsegment.put_metadata("response", result)

return result
17 changes: 17 additions & 0 deletions docs/examples/tutorial/event_handler_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from aws_lambda_powertools.event_handler import APIGatewayRestResolver

app = APIGatewayRestResolver()


@app.get("/hello/<name>")
def hello_name(name):
return {"message": f"hello {name}!"}


@app.get("/hello")
def hello():
return {"message": "hello unknown!"}


def lambda_handler(event, context):
return app.resolve(event, context)
29 changes: 29 additions & 0 deletions docs/examples/tutorial/generate_traces_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from aws_xray_sdk.core import xray_recorder

from aws_lambda_powertools import Logger
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.logging import correlation_paths

logger = Logger(service="APP")

app = APIGatewayRestResolver()


@app.get("/hello/<name>")
@xray_recorder.capture("hello_name")
def hello_name(name):
logger.info(f"Request from {name} received")
return {"message": f"hello {name}!"}


@app.get("/hello")
@xray_recorder.capture("hello")
def hello():
logger.info("Request from unknown received")
return {"message": "hello unknown!"}


@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST, log_event=True)
@xray_recorder.capture("handler")
def lambda_handler(event, context):
return app.resolve(event, context)
31 changes: 31 additions & 0 deletions docs/examples/tutorial/generate_traces_template.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Sample SAM Template for powertools-quickstart
Globals:
Function:
Timeout: 3
Api:
TracingEnabled: true
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.9
Tracing: Active
Events:
HelloWorld:
Type: Api
Properties:
Path: /hello
Method: get
HelloWorldName:
Type: Api
Properties:
Path: /hello/{name}
Method: get
Outputs:
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
Loading