Skip to content

Commit 9c4c644

Browse files
authored
feature: extract code examples to python files (#24)
1 parent dc35984 commit 9c4c644

File tree

14 files changed

+134
-76
lines changed

14 files changed

+134
-76
lines changed

.flake8

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
[flake8]
2-
exclude = docs, .eggs, setup.py, example, .cdk,out, .git, dist, *.md, *.yaml, *.txt, *.ini
2+
exclude = .eggs, setup.py, example, .cdk,out, .git, dist, *.md, *.yaml, *.txt, *.ini
33
ignore = E203, E266, W503, BLK100, W291, I004
44
max-line-length = 150
55
max-complexity = 15

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ dev:
88

99
lint:
1010
@echo "Running flake8"
11-
flake8 service/* tests/*
11+
flake8 service/* tests/* docs/examples/*
1212

1313
complex:
1414
@echo "Running Radon"

docs/best_practices/environment_variables.md

Lines changed: 9 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -27,20 +27,10 @@ Read more about the importance of validating environment variables and how this
2727
You need to define all your environment variables in a Pydantic schema class that extend Pydantic's BaseModel class.
2828

2929
For example:
30-
=== "schemas/env_vars.py"
3130

32-
```python hl_lines="5"
33-
from typing import Literal
34-
35-
from pydantic import BaseModel, HttpUrl, constr
36-
37-
class MyHandlerEnvVars(BaseModel):
38-
REST_API: HttpUrl
39-
ROLE_ARN: constr(min_length=20, max_length=2048)
40-
POWERTOOLS_SERVICE_NAME: constr(min_length=1)
41-
LOG_LEVEL: Literal['DEBUG', 'INFO', 'ERROR', 'CRITICAL', 'WARNING', 'EXCEPTION']
42-
43-
```
31+
```python hl_lines="6" title="schemas/env_vars.py"
32+
--8<-- "docs/examples/best_practices/environment_variables/env_vars.py"
33+
```
4434

4535
All Pydantic schemas extend Pydantic’s ‘BaseModel’ class, turning them into a dataclass.
4636

@@ -60,23 +50,10 @@ The decorator 'init_environment_variables' is defined under the utility folder *
6050

6151
The decorator requires a **model** parameter, which in this example is the name of the schema class we defined above.
6252

63-
=== "handlers/my_handler.py"
64-
65-
```python hl_lines="11"
66-
import json
67-
from http import HTTPStatus
68-
from typing import Any, Dict
69-
70-
from aws_lambda_powertools.utilities.typing import LambdaContext
71-
72-
from service.handlers.schemas.env_vars import MyHandlerEnvVars
73-
from service.handlers.utils.env_vars_parser import init_environment_variables
74-
7553

76-
@init_environment_variables(model=MyHandlerEnvVars)
77-
def my_handler(event: Dict[str, Any], context: LambdaContext) -> Dict[str, Any]:
78-
return {'statusCode': HTTPStatus.OK, 'headers': {'Content-Type': 'application/json'}, 'body': json.dumps({'message': 'success'})}
79-
```
54+
```python hl_lines="11" title="handlers/my_handler.py"
55+
--8<-- "docs/examples/best_practices/environment_variables/my_handler.py"
56+
```
8057

8158
## **Global Getter Usage**
8259
The getter function 'get_environment_variables' is defined under the utility folder **service.utils.env_vars_parser.py** and imported in the handler.
@@ -85,25 +62,9 @@ The getter function returns a parsed and validated global instance of the enviro
8562

8663
It can be used *anywhere* in the function code, not just the handler.
8764

88-
=== "handlers/my_handler.py"
89-
90-
```python hl_lines="13"
91-
import json
92-
from http import HTTPStatus
93-
from typing import Any, Dict
94-
95-
from aws_lambda_powertools.utilities.typing import LambdaContext
96-
97-
from service.handlers.schemas.env_vars import MyHandlerEnvVars
98-
from service.handlers.utils.env_vars_parser import get_environment_variables, init_environment_variables
99-
100-
101-
@init_environment_variables(model=MyHandlerEnvVars)
102-
def my_handler(event: Dict[str, Any], context: LambdaContext) -> Dict[str, Any]:
103-
env_vars: MyHandlerEnvVars = get_environment_variables(model=MyHandlerEnvVars)
104-
return {'statusCode': HTTPStatus.OK, 'headers': {'Content-Type': 'application/json'}, 'body': json.dumps({'message': 'success'})}
105-
```
106-
65+
```python hl_lines="13" title="handlers/my_handler.py"
66+
--8<-- "docs/examples/best_practices/environment_variables/getter.py"
67+
```
10768

10869

10970
## **More Details**

docs/best_practices/input_validation.md

Lines changed: 3 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -69,29 +69,9 @@ The parser is a called with the function 'parse'.
6969

7070
Use the envelope class that matches the AWS service that triggers your AWS Lambda function.
7171

72-
=== "my_handler.py"
73-
74-
```python hl_lines="14"
75-
from typing import Any, Dict
76-
77-
from aws_lambda_powertools.utilities.parser import ValidationError, parse
78-
from aws_lambda_powertools.utilities.parser.envelopes import ApiGatewayEnvelope
79-
from aws_lambda_powertools.utilities.typing import LambdaContext
80-
81-
from service.handlers.schemas.input import Input
82-
83-
84-
def my_handler(event: Dict[str, Any], context: LambdaContext):
85-
# validate input
86-
try:
87-
# we want to extract and parse the HTTP body from the api gw envelope
88-
input: Input = parse(event=event, model=Input, envelope=ApiGatewayEnvelope)
89-
except (ValidationError, TypeError) as err:
90-
# log error, return BAD_REQUEST
91-
92-
# process input
93-
94-
```
72+
```python hl_lines="13" title="my_handler.py"
73+
--8<-- "docs/examples/best_practices/input_validation/my_handler.py"
74+
```
9575

9676
## Accessing Envelope Metadata
9777

docs/best_practices/logger.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@ It’s a wrapper of Python’s logging library that provides extra capabilities
1414

1515

1616
## **Usage in Handler**
17-
The logger is a singleton which is defined under the utility folder **service.utils.observability.py** and imported in the handler.
17+
18+
```python hl_lines="8 12 13" title="my_handler.py"
19+
--8<-- "docs/examples/best_practices/logger/my_handler.py"
20+
```
1821

1922
## **Blog Reference**
2023
Read more about the importance of the logger and how to use AWS CloudWatch logs in my blog. Click [**HERE**](https://www.ranthebuilder.cloud/post/aws-lambda-cookbook-elevate-your-handler-s-code-part-1-logging){:target="_blank" rel="noopener"}

docs/best_practices/metrics.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@ These metrics can be visualized through [Amazon CloudWatch Console](https://cons
2020

2121

2222
## **Usage in Handler**
23-
The metrics is a singleton which is defined under the utility folder **service.utils.observability.py** and imported in the handler.
23+
24+
```python hl_lines="11 14 16" title="my_handler.py"
25+
--8<-- "docs/examples/best_practices/metrics/my_handler.py"
26+
```
2427

2528
## **Blog Reference**
2629
Read more about the importance of the business KPis and metrics in my blog. Click [**HERE**](https://www.ranthebuilder.cloud/post/aws-lambda-cookbook-elevate-your-handler-s-code-part-3-business-domain-observability){:target="_blank" rel="noopener"}

docs/best_practices/tracer.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@ Tracer is a thin wrapper for [AWS X-Ray Python SDK](https://github.com/aws/aws-x
1414

1515

1616
## **Usage in Handler**
17-
The tracer is a singleton which is defined under the utility folder **service.utils.observability.py** and imported in the handler.
17+
18+
```python hl_lines="11 14 19" title="my_handler.py"
19+
--8<-- "docs/examples/best_practices/tracer/my_handler.py"
20+
```
1821

1922
## **Blog Reference**
2023
Read more about the importance of observability and traces in my blog. Click [**HERE**](https://www.ranthebuilder.cloud/post/aws-lambda-cookbook-elevate-your-handler-s-code-part-2-observability){:target="_blank" rel="noopener"}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from typing import Literal
2+
3+
from pydantic import BaseModel, HttpUrl, constr
4+
5+
6+
class MyHandlerEnvVars(BaseModel):
7+
REST_API: HttpUrl
8+
ROLE_ARN: constr(min_length=20, max_length=2048)
9+
POWERTOOLS_SERVICE_NAME: constr(min_length=1)
10+
LOG_LEVEL: Literal['DEBUG', 'INFO', 'ERROR', 'CRITICAL', 'WARNING', 'EXCEPTION']
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import json
2+
from http import HTTPStatus
3+
from typing import Any, Dict
4+
5+
from aws_lambda_powertools.utilities.typing import LambdaContext
6+
7+
from service.handlers.schemas.env_vars import MyHandlerEnvVars
8+
from service.handlers.utils.env_vars_parser import get_environment_variables, init_environment_variables
9+
10+
11+
@init_environment_variables(model=MyHandlerEnvVars)
12+
def my_handler(event: Dict[str, Any], context: LambdaContext) -> Dict[str, Any]:
13+
env_vars: MyHandlerEnvVars = get_environment_variables(model=MyHandlerEnvVars) # noqa: F841
14+
return {'statusCode': HTTPStatus.OK, 'headers': {'Content-Type': 'application/json'}, 'body': json.dumps({'message': 'success'})}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import json
2+
from http import HTTPStatus
3+
from typing import Any, Dict
4+
5+
from aws_lambda_powertools.utilities.typing import LambdaContext
6+
7+
from service.handlers.schemas.env_vars import MyHandlerEnvVars
8+
from service.handlers.utils.env_vars_parser import get_environment_variables, init_environment_variables
9+
10+
11+
@init_environment_variables(model=MyHandlerEnvVars)
12+
def my_handler(event: Dict[str, Any], context: LambdaContext) -> Dict[str, Any]:
13+
env_vars: MyHandlerEnvVars = get_environment_variables(model=MyHandlerEnvVars) # noqa: F841
14+
return {'statusCode': HTTPStatus.OK, 'headers': {'Content-Type': 'application/json'}, 'body': json.dumps({'message': 'success'})}

0 commit comments

Comments
 (0)