forked from aws-powertools/powertools-lambda-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetting_started_middleware_tracer_function.py
41 lines (29 loc) · 1.15 KB
/
getting_started_middleware_tracer_function.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import time
from typing import Callable
import requests
from requests import Response
from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.middleware_factory import lambda_handler_decorator
from aws_lambda_powertools.utilities.typing import LambdaContext
app = APIGatewayRestResolver()
@lambda_handler_decorator(trace_execution=True)
def middleware_with_tracing(
handler: Callable[[dict, LambdaContext], dict],
event: dict,
context: LambdaContext,
) -> dict:
start_time = time.time()
response = handler(event, context)
execution_time = time.time() - start_time
# adding custom headers in response object after lambda executing
response["headers"]["execution_time"] = execution_time
response["headers"]["aws_request_id"] = context.aws_request_id
return response
@app.get("/products")
def create_product() -> dict:
product: Response = requests.get("https://dummyjson.com/products/1")
product.raise_for_status()
return {"product": product.json()}
@middleware_with_tracing
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return app.resolve(event, context)