forked from aws-powertools/powertools-lambda-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
- Loading branch information
1 parent
7e76868
commit 1158cab
Showing
18 changed files
with
534 additions
and
511 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/" |
Oops, something went wrong.