Skip to content

Commit 1158cab

Browse files
committed
fix(docs): Extract tutorial code examples
Changes: - Extract code examples - Run isort and black - Update line highlights - Add make task to format and lint examples Related to: - aws-powertools#1064
1 parent 7e76868 commit 1158cab

18 files changed

+534
-511
lines changed

Diff for: Makefile

+8
Original file line numberDiff line numberDiff line change
@@ -90,3 +90,11 @@ changelog:
9090

9191
mypy:
9292
poetry run mypy --pretty aws_lambda_powertools
93+
94+
format-examples:
95+
poetry run isort docs/examples
96+
poetry run black docs/examples/*/*.py
97+
98+
lint-examples:
99+
poetry run python3 -m py_compile docs/examples/*/*.py
100+
cfn-lint docs/examples/*/*.yml

Diff for: docs/examples/tutorial/add_route_hello_by_name.py

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import json
2+
3+
4+
def hello_name(name):
5+
return {"statusCode": 200, "body": json.dumps({"message": f"hello {name}!"})}
6+
7+
8+
def lambda_handler(event, context):
9+
name = event["pathParameters"]["name"]
10+
return hello_name(name)

Diff for: docs/examples/tutorial/add_route_temaplate.yml

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
AWSTemplateFormatVersion: "2010-09-09"
2+
Transform: AWS::Serverless-2016-10-31
3+
Description: Sample SAM Template for powertools-quickstart
4+
Globals:
5+
Function:
6+
Timeout: 3
7+
Resources:
8+
HelloWorldFunction:
9+
Type: AWS::Serverless::Function
10+
Properties:
11+
CodeUri: hello_world/
12+
Handler: app.lambda_handler
13+
Runtime: python3.9
14+
Events:
15+
HelloWorld:
16+
Type: Api
17+
Properties:
18+
Path: /hello
19+
Method: get
20+
21+
HelloWorldByNameFunctionName:
22+
Type: AWS::Serverless::Function
23+
Properties:
24+
CodeUri: hello_world/
25+
Handler: hello_by_name.lambda_handler
26+
Runtime: python3.9
27+
Events:
28+
HelloWorldName:
29+
Type: Api
30+
Properties:
31+
Path: /hello/{name}
32+
Method: get
33+
Outputs:
34+
HelloWorldApi:
35+
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
36+
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"

Diff for: docs/examples/tutorial/code_example_app.py

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import json
2+
3+
4+
def hello():
5+
return {"statusCode": 200, "body": json.dumps({"message": "hello unknown!"})}
6+
7+
8+
def lambda_handler(event, context):
9+
return hello()

Diff for: docs/examples/tutorial/code_example_template.yml

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
AWSTemplateFormatVersion: '2010-09-09'
2+
Transform: AWS::Serverless-2016-10-31
3+
Description: Sample SAM Template for powertools-quickstart
4+
Globals:
5+
Function:
6+
Timeout: 3
7+
Resources:
8+
HelloWorldFunction:
9+
Type: AWS::Serverless::Function
10+
Properties:
11+
CodeUri: hello_world/
12+
Handler: app.lambda_handler
13+
Runtime: python3.9
14+
Architectures:
15+
- x86_64
16+
Events:
17+
HelloWorld:
18+
Type: Api
19+
Properties:
20+
Path: /hello
21+
Method: get
22+
Outputs:
23+
HelloWorldApi:
24+
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
25+
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"

Diff for: docs/examples/tutorial/create_metrics_app.py

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import os
2+
3+
import boto3
4+
5+
from aws_lambda_powertools import Logger, Tracer
6+
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
7+
from aws_lambda_powertools.logging import correlation_paths
8+
9+
cold_start = True
10+
metric_namespace = "MyApp"
11+
12+
logger = Logger(service="APP")
13+
tracer = Tracer(service="APP")
14+
metrics = boto3.client("cloudwatch")
15+
app = APIGatewayRestResolver()
16+
17+
18+
@tracer.capture_method
19+
def add_greeting_metric(service: str = "APP"):
20+
function_name = os.getenv("AWS_LAMBDA_FUNCTION_NAME", "undefined")
21+
service_dimension = {"Name": "service", "Value": service}
22+
function_dimension = {"Name": "function_name", "Value": function_name}
23+
is_cold_start = True
24+
25+
global cold_start
26+
if cold_start:
27+
cold_start = False
28+
else:
29+
is_cold_start = False
30+
31+
return metrics.put_metric_data(
32+
MetricData=[
33+
{
34+
"MetricName": "SuccessfulGreetings",
35+
"Dimensions": [service_dimension],
36+
"Unit": "Count",
37+
"Value": 1,
38+
},
39+
{
40+
"MetricName": "ColdStart",
41+
"Dimensions": [service_dimension, function_dimension],
42+
"Unit": "Count",
43+
"Value": int(is_cold_start),
44+
},
45+
],
46+
Namespace=metric_namespace,
47+
)
48+
49+
50+
@app.get("/hello/<name>")
51+
@tracer.capture_method
52+
def hello_name(name):
53+
tracer.put_annotation(key="User", value=name)
54+
logger.info(f"Request from {name} received")
55+
add_greeting_metric()
56+
return {"message": f"hello {name}!"}
57+
58+
59+
@app.get("/hello")
60+
@tracer.capture_method
61+
def hello():
62+
tracer.put_annotation(key="User", value="unknown")
63+
logger.info("Request from unknown received")
64+
add_greeting_metric()
65+
return {"message": "hello unknown!"}
66+
67+
68+
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST, log_event=True)
69+
@tracer.capture_lambda_handler
70+
def lambda_handler(event, context):
71+
return app.resolve(event, context)

Diff for: docs/examples/tutorial/create_metrics_template.yml

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
AWSTemplateFormatVersion: "2010-09-09"
2+
Transform: AWS::Serverless-2016-10-31
3+
Description: Sample SAM Template for powertools-quickstart
4+
Globals:
5+
Function:
6+
Timeout: 3
7+
Resources:
8+
HelloWorldFunction:
9+
Type: AWS::Serverless::Function
10+
Properties:
11+
CodeUri: hello_world/
12+
Handler: app.lambda_handler
13+
Runtime: python3.9
14+
Tracing: Active
15+
Events:
16+
HelloWorld:
17+
Type: Api
18+
Properties:
19+
Path: /hello
20+
Method: get
21+
HelloWorldName:
22+
Type: Api
23+
Properties:
24+
Path: /hello/{name}
25+
Method: get
26+
Policies:
27+
- CloudWatchPutMetricPolicy: {}
28+
Outputs:
29+
HelloWorldApi:
30+
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
31+
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"

Diff for: docs/examples/tutorial/create_own_router_app.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import json
2+
3+
4+
def hello_name(event, **kargs):
5+
username = event["pathParameters"]["name"]
6+
return {"statusCode": 200, "body": json.dumps({"message": f"hello {username}!"})}
7+
8+
9+
def hello(**kargs):
10+
return {"statusCode": 200, "body": json.dumps({"message": "hello unknown!"})}
11+
12+
13+
class Router:
14+
def __init__(self):
15+
self.routes = {}
16+
17+
def set(self, path, method, handler):
18+
self.routes[f"{path}-{method}"] = handler
19+
20+
def get(self, path, method):
21+
try:
22+
route = self.routes[f"{path}-{method}"]
23+
except KeyError:
24+
raise RuntimeError(f"Cannot route request to the correct method. path={path}, method={method}")
25+
return route
26+
27+
28+
router = Router()
29+
router.set(path="/hello", method="GET", handler=hello)
30+
router.set(path="/hello/{name}", method="GET", handler=hello_name)
31+
32+
33+
def lambda_handler(event, context):
34+
path = event["resource"]
35+
http_method = event["httpMethod"]
36+
method = router.get(path=path, method=http_method)
37+
return method(event=event)
+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
AWSTemplateFormatVersion: "2010-09-09"
2+
Transform: AWS::Serverless-2016-10-31
3+
Description: Sample SAM Template for powertools-quickstart
4+
Globals:
5+
Function:
6+
Timeout: 3
7+
Resources:
8+
HelloWorldFunction:
9+
Type: AWS::Serverless::Function
10+
Properties:
11+
CodeUri: hello_world/
12+
Handler: app.lambda_handler
13+
Runtime: python3.9
14+
Events:
15+
HelloWorld:
16+
Type: Api
17+
Properties:
18+
Path: /hello
19+
Method: get
20+
HelloWorldName:
21+
Type: Api
22+
Properties:
23+
Path: /hello/{name}
24+
Method: get
25+
Outputs:
26+
HelloWorldApi:
27+
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
28+
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"

Diff for: docs/examples/tutorial/enrich_generate_traces_app.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from aws_xray_sdk.core import patch_all, xray_recorder
2+
3+
from aws_lambda_powertools import Logger
4+
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
5+
from aws_lambda_powertools.logging import correlation_paths
6+
7+
logger = Logger(service="APP")
8+
9+
app = APIGatewayRestResolver()
10+
cold_start = True
11+
patch_all()
12+
13+
14+
@app.get("/hello/<name>")
15+
@xray_recorder.capture("hello_name")
16+
def hello_name(name):
17+
subsegment = xray_recorder.current_subsegment()
18+
subsegment.put_annotation(key="User", value=name)
19+
logger.info(f"Request from {name} received")
20+
return {"message": f"hello {name}!"}
21+
22+
23+
@app.get("/hello")
24+
@xray_recorder.capture("hello")
25+
def hello():
26+
subsegment = xray_recorder.current_subsegment()
27+
subsegment.put_annotation(key="User", value="unknown")
28+
logger.info("Request from unknown received")
29+
return {"message": "hello unknown!"}
30+
31+
32+
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST, log_event=True)
33+
@xray_recorder.capture("handler")
34+
def lambda_handler(event, context):
35+
global cold_start
36+
37+
subsegment = xray_recorder.current_subsegment()
38+
if cold_start:
39+
subsegment.put_annotation(key="ColdStart", value=cold_start)
40+
cold_start = False
41+
else:
42+
subsegment.put_annotation(key="ColdStart", value=cold_start)
43+
44+
result = app.resolve(event, context)
45+
subsegment.put_metadata("response", result)
46+
47+
return result

Diff for: docs/examples/tutorial/event_handler_app.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
2+
3+
app = APIGatewayRestResolver()
4+
5+
6+
@app.get("/hello/<name>")
7+
def hello_name(name):
8+
return {"message": f"hello {name}!"}
9+
10+
11+
@app.get("/hello")
12+
def hello():
13+
return {"message": "hello unknown!"}
14+
15+
16+
def lambda_handler(event, context):
17+
return app.resolve(event, context)

Diff for: docs/examples/tutorial/generate_traces_app.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from aws_xray_sdk.core import xray_recorder
2+
3+
from aws_lambda_powertools import Logger
4+
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
5+
from aws_lambda_powertools.logging import correlation_paths
6+
7+
logger = Logger(service="APP")
8+
9+
app = APIGatewayRestResolver()
10+
11+
12+
@app.get("/hello/<name>")
13+
@xray_recorder.capture("hello_name")
14+
def hello_name(name):
15+
logger.info(f"Request from {name} received")
16+
return {"message": f"hello {name}!"}
17+
18+
19+
@app.get("/hello")
20+
@xray_recorder.capture("hello")
21+
def hello():
22+
logger.info("Request from unknown received")
23+
return {"message": "hello unknown!"}
24+
25+
26+
@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST, log_event=True)
27+
@xray_recorder.capture("handler")
28+
def lambda_handler(event, context):
29+
return app.resolve(event, context)

Diff for: docs/examples/tutorial/generate_traces_template.yml

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
AWSTemplateFormatVersion: "2010-09-09"
2+
Transform: AWS::Serverless-2016-10-31
3+
Description: Sample SAM Template for powertools-quickstart
4+
Globals:
5+
Function:
6+
Timeout: 3
7+
Api:
8+
TracingEnabled: true
9+
Resources:
10+
HelloWorldFunction:
11+
Type: AWS::Serverless::Function
12+
Properties:
13+
CodeUri: hello_world/
14+
Handler: app.lambda_handler
15+
Runtime: python3.9
16+
Tracing: Active
17+
Events:
18+
HelloWorld:
19+
Type: Api
20+
Properties:
21+
Path: /hello
22+
Method: get
23+
HelloWorldName:
24+
Type: Api
25+
Properties:
26+
Path: /hello/{name}
27+
Method: get
28+
Outputs:
29+
HelloWorldApi:
30+
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
31+
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"

0 commit comments

Comments
 (0)