Skip to content

Commit cd4cd41

Browse files
Merge branch 'develop' into dependabot/docker/docs/squidfunk/mkdocs-material-sha25695f2ff42251979c043d6cb5b1c82e6ae8189e57e02105813dd1ce124021a418b
2 parents 2cd45c8 + a48f9bf commit cd4cd41

File tree

64 files changed

+121
-176
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

64 files changed

+121
-176
lines changed

.github/workflows/quality_check.yml

+2
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ jobs:
6363
run: make dev-quality-code
6464
- name: Checking third-party library licenses
6565
run: make check-licenses
66+
- name: Checking and enforcing format
67+
run: make format-check
6668
- name: Formatting and Linting
6769
run: make lint
6870
- name: Static type checking

.pre-commit-config.yaml

+4-4
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,13 @@ repos:
1212
- id: check-toml
1313
- repo: local
1414
hooks:
15-
- id: black
16-
name: formatting::black
17-
entry: poetry run black
15+
- id: ruff
16+
name: formatting::ruff
17+
entry: poetry run ruff format
1818
language: system
1919
types: [python]
2020
- id: ruff
21-
name: linting-format::ruff
21+
name: linting::ruff
2222
entry: poetry run ruff check
2323
language: system
2424
types: [python]

Makefile

+4-1
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,11 @@ dev-gitpod:
2525
check-licenses:
2626
poetry run licensecheck -u poetry:dev
2727

28+
format-check:
29+
poetry run ruff format aws_lambda_powertools tests examples --check
30+
2831
format:
29-
poetry run black aws_lambda_powertools tests examples
32+
poetry run ruff format aws_lambda_powertools tests examples
3033

3134
lint: format
3235
poetry run ruff check aws_lambda_powertools tests examples

aws_lambda_powertools/event_handler/api_gateway.py

-2
Original file line numberDiff line numberDiff line change
@@ -1604,7 +1604,6 @@ def _validate_response_validation_error_http_code(
16041604
response_validation_error_http_code: HTTPStatus | int | None,
16051605
enable_validation: bool,
16061606
) -> HTTPStatus:
1607-
16081607
if response_validation_error_http_code and not enable_validation:
16091608
msg = "'response_validation_error_http_code' cannot be set when enable_validation is False."
16101609
raise ValueError(msg)
@@ -1613,7 +1612,6 @@ def _validate_response_validation_error_http_code(
16131612
not isinstance(response_validation_error_http_code, HTTPStatus)
16141613
and response_validation_error_http_code is not None
16151614
):
1616-
16171615
try:
16181616
response_validation_error_http_code = HTTPStatus(response_validation_error_http_code)
16191617
except ValueError:

aws_lambda_powertools/event_handler/bedrock_agent.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -110,11 +110,11 @@ def get( # type: ignore[override]
110110
tags: list[str] | None = None,
111111
operation_id: str | None = None,
112112
include_in_schema: bool = True,
113+
openapi_extensions: dict[str, Any] | None = None,
113114
deprecated: bool = False,
114115
custom_response_validation_http_code: int | HTTPStatus | None = None,
115116
middlewares: list[Callable[..., Any]] | None = None,
116117
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
117-
openapi_extensions = None
118118
security = None
119119

120120
return super().get(
@@ -151,11 +151,11 @@ def post( # type: ignore[override]
151151
tags: list[str] | None = None,
152152
operation_id: str | None = None,
153153
include_in_schema: bool = True,
154+
openapi_extensions: dict[str, Any] | None = None,
154155
deprecated: bool = False,
155156
custom_response_validation_http_code: int | HTTPStatus | None = None,
156157
middlewares: list[Callable[..., Any]] | None = None,
157158
):
158-
openapi_extensions = None
159159
security = None
160160

161161
return super().post(
@@ -192,11 +192,11 @@ def put( # type: ignore[override]
192192
tags: list[str] | None = None,
193193
operation_id: str | None = None,
194194
include_in_schema: bool = True,
195+
openapi_extensions: dict[str, Any] | None = None,
195196
deprecated: bool = False,
196197
custom_response_validation_http_code: int | HTTPStatus | None = None,
197198
middlewares: list[Callable[..., Any]] | None = None,
198199
):
199-
openapi_extensions = None
200200
security = None
201201

202202
return super().put(
@@ -233,11 +233,11 @@ def patch( # type: ignore[override]
233233
tags: list[str] | None = None,
234234
operation_id: str | None = None,
235235
include_in_schema: bool = True,
236+
openapi_extensions: dict[str, Any] | None = None,
236237
deprecated: bool = False,
237238
custom_response_validation_http_code: int | HTTPStatus | None = None,
238239
middlewares: list[Callable] | None = None,
239240
):
240-
openapi_extensions = None
241241
security = None
242242

243243
return super().patch(
@@ -274,11 +274,11 @@ def delete( # type: ignore[override]
274274
tags: list[str] | None = None,
275275
operation_id: str | None = None,
276276
include_in_schema: bool = True,
277+
openapi_extensions: dict[str, Any] | None = None,
277278
deprecated: bool = False,
278279
custom_response_validation_http_code: int | HTTPStatus | None = None,
279280
middlewares: list[Callable[..., Any]] | None = None,
280281
):
281-
openapi_extensions = None
282282
security = None
283283

284284
return super().delete(
@@ -325,6 +325,7 @@ def get_openapi_json_schema( # type: ignore[override]
325325
license_info: License | None = None,
326326
security_schemes: dict[str, SecurityScheme] | None = None,
327327
security: list[dict[str, list[str]]] | None = None,
328+
openapi_extensions: dict[str, Any] | None = None,
328329
) -> str:
329330
"""
330331
Returns the OpenAPI schema as a JSON serializable dict.
@@ -365,8 +366,6 @@ def get_openapi_json_schema( # type: ignore[override]
365366
"""
366367
from aws_lambda_powertools.event_handler.openapi.compat import model_json
367368

368-
openapi_extensions = None
369-
370369
schema = super().get_openapi_schema(
371370
title=title,
372371
version=version,

aws_lambda_powertools/event_handler/openapi/models.py

-1
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ class OpenAPIExtensions(BaseModel):
3636
@model_validator(mode="before")
3737
def serialize_openapi_extension_v2(self):
3838
if isinstance(self, dict) and self.get("openapi_extensions"):
39-
4039
openapi_extension_value = self.get("openapi_extensions")
4140

4241
for extension_key in openapi_extension_value:

aws_lambda_powertools/logging/logger.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1205,15 +1205,15 @@ def flush_buffer(self) -> None:
12051205
buffer = self._buffer_cache.get(tracer_id)
12061206
if not buffer:
12071207
return
1208-
1208+
12091209
if not self._buffer_config:
12101210
return
1211-
1211+
12121212
# Check ALC level against buffer level
12131213
lambda_log_level = self._get_aws_lambda_log_level()
12141214
if lambda_log_level:
12151215
# Check if buffer level is less verbose than ALC
1216-
if (logging.getLevelName(lambda_log_level) > logging.getLevelName(self._buffer_config.buffer_at_verbosity)):
1216+
if logging.getLevelName(lambda_log_level) > logging.getLevelName(self._buffer_config.buffer_at_verbosity):
12171217
warnings.warn(
12181218
"Advanced Logging Controls (ALC) Log Level is less verbose than Log Buffering Log Level. "
12191219
"Some logs might be missing",

aws_lambda_powertools/utilities/batch/base.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -296,8 +296,7 @@ def _clean(self):
296296

297297
if self._entire_batch_failed() and self.raise_on_entire_batch_failure:
298298
raise BatchProcessingError(
299-
msg=f"All records failed processing. {len(self.exceptions)} individual errors logged "
300-
f"separately below.",
299+
msg=f"All records failed processing. {len(self.exceptions)} individual errors logged separately below.",
301300
child_exceptions=self.exceptions,
302301
)
303302

aws_lambda_powertools/utilities/data_classes/code_pipeline_job_event.py

-1
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,6 @@ def put_artifact(self, artifact_name: str, body: Any, content_type: str) -> None
314314
# So we are using if/else instead.
315315

316316
if self.data.encryption_key:
317-
318317
encryption_key_id = self.data.encryption_key.get_id
319318
encryption_key_type = self.data.encryption_key.get_type
320319
if encryption_key_type == "KMS":

aws_lambda_powertools/utilities/data_classes/transfer_family_event.py

-2
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ def source_ip(self) -> str:
3939

4040

4141
class TransferFamilyAuthorizerResponse:
42-
4342
def _build_authentication_response(
4443
self,
4544
role_arn: str,
@@ -51,7 +50,6 @@ def _build_authentication_response(
5150
user_uid: int | None = None,
5251
public_keys: str | None = None,
5352
) -> dict[str, Any]:
54-
5553
response: dict[str, Any] = {}
5654

5755
if home_directory_type == "PATH":

aws_lambda_powertools/utilities/data_masking/provider/base.py

-1
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,6 @@ def erase(
8282
masking_rules: dict | None = None,
8383
**kwargs,
8484
) -> Any:
85-
8685
result: Any = DATA_MASKING_STRING
8786

8887
if not any([dynamic_mask, custom_mask, regex_pattern, mask_format, masking_rules]):

aws_lambda_powertools/utilities/idempotency/serialization/dataclass.py

-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ def from_dict(self, data: dict) -> DataClass:
3838

3939
@classmethod
4040
def instantiate(cls, model_type: Any) -> BaseIdempotencySerializer:
41-
4241
model_type = get_actual_type(model_type=model_type)
4342

4443
if model_type is None:

aws_lambda_powertools/utilities/idempotency/serialization/pydantic.py

-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ def from_dict(self, data: dict) -> BaseModel:
3535

3636
@classmethod
3737
def instantiate(cls, model_type: Any) -> BaseIdempotencySerializer:
38-
3938
model_type = get_actual_type(model_type=model_type)
4039

4140
if model_type is None:

docs/core/event_handler/bedrock_agents.md

+10
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,16 @@ To implement these customizations, include extra parameters when defining your r
313313
--8<-- "examples/event_handler_bedrock_agents/src/customizing_bedrock_api_operations.py"
314314
```
315315

316+
#### Enabling user confirmation
317+
318+
You can enable user confirmation with Bedrock Agents to have your application ask for explicit user approval before invoking an action.
319+
320+
```python hl_lines="14" title="enabling_user_confirmation.py" title="Enabling user confirmation"
321+
--8<-- "examples/event_handler_bedrock_agents/src/enabling_user_confirmation.py"
322+
```
323+
324+
1. Add an openapi extension
325+
316326
## Testing your code
317327

318328
Test your routes by passing an [Agent for Amazon Bedrock proxy event](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-lambda.html#agents-lambda-input) request:

examples/batch_processing/src/getting_started_error_handling.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@
1212
logger = Logger()
1313

1414

15-
class InvalidPayload(Exception):
16-
...
15+
class InvalidPayload(Exception): ...
1716

1817

1918
@tracer.capture_method

examples/data_masking/src/aws_encryption_provider_example.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@
1616
local_cache_capacity=200,
1717
max_cache_age_seconds=400,
1818
max_messages_encrypted=200,
19-
max_bytes_encrypted=2000)
19+
max_bytes_encrypted=2000,
20+
)
2021

2122
data_masker = DataMasking(provider=encryption_provider)
2223

examples/event_handler_bedrock_agents/cdk/bedrock_agent_stack.py

-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88

99

1010
class AgentsCdkStack(Stack):
11-
1211
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
1312
super().__init__(scope, construct_id, **kwargs)
1413

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from time import time
2+
3+
from aws_lambda_powertools import Logger
4+
from aws_lambda_powertools.event_handler import BedrockAgentResolver
5+
from aws_lambda_powertools.utilities.typing import LambdaContext
6+
7+
logger = Logger()
8+
app = BedrockAgentResolver()
9+
10+
11+
@app.get(
12+
"/current_time",
13+
description="Gets the current time in seconds",
14+
openapi_extensions={"x-requireConfirmation": "ENABLED"}, # (1)!
15+
)
16+
def current_time() -> int:
17+
return int(time())
18+
19+
20+
@logger.inject_lambda_context
21+
def lambda_handler(event: dict, context: LambdaContext):
22+
return app.resolve(event, context)
23+
24+
25+
if __name__ == "__main__":
26+
print(app.get_openapi_json_schema())

examples/event_handler_graphql/src/enable_exceptions_batch_resolver.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,7 @@
1414
}
1515

1616

17-
class PostRelatedNotFound(Exception):
18-
...
17+
class PostRelatedNotFound(Exception): ...
1918

2019

2120
@app.batch_resolver(type_name="Query", field_name="relatedPosts", raise_on_error=True) # (1)!

examples/event_handler_rest/src/raising_http_errors.py

+1
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ def service_error():
6666
def service_unavailable_error():
6767
raise ServiceUnavailableError("Service is temporarily unavailable") # HTTP 503
6868

69+
6970
@app.get("/todos")
7071
@tracer.capture_method
7172
def get_todos():

examples/event_sources/src/cloudWatchDashboard.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,6 @@ def lambda_handler(event: CloudWatchDashboardCustomWidgetEvent, context):
2626
"markdown": f"""
2727
Dashboard: {event.widget_context.dashboard_name}
2828
Time Range: {time_range.start} to {time_range.end}
29-
Theme: {event.widget_context.theme or 'default'}
29+
Theme: {event.widget_context.theme or "default"}
3030
""",
3131
}

examples/event_sources/src/s3_batch_operation.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -33,5 +33,4 @@ def lambda_handler(event: S3BatchOperationEvent, context: LambdaContext):
3333
return response.asdict()
3434

3535

36-
def do_some_work(s3_client, src_bucket: str, src_key: str):
37-
...
36+
def do_some_work(s3_client, src_bucket: str, src_key: str): ...

examples/homepage/install/arm64/cdk_arm64.py

-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44

55
class SampleApp(Stack):
6-
76
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
87
super().__init__(scope, construct_id, **kwargs)
98

examples/homepage/install/sar/cdk_sar.py

-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010

1111

1212
class SampleApp(Stack):
13-
1413
def __init__(self, scope: Construct, id_: str) -> None:
1514
super().__init__(scope, id_)
1615

examples/homepage/install/x86_64/cdk_x86.py

-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44

55
class SampleApp(Stack):
6-
76
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
87
super().__init__(scope, construct_id, **kwargs)
98

examples/idempotency/src/working_with_custom_idempotency_key_prefix.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ class Payment:
2222
class PaymentError(Exception): ...
2323

2424

25-
@idempotent(persistence_store=persistence_layer, key_prefix="my_custom_prefix") # (1)!
25+
@idempotent(persistence_store=persistence_layer, key_prefix="my_custom_prefix") # (1)!
2626
def lambda_handler(event: dict, context: LambdaContext):
2727
try:
2828
payment: Payment = create_subscription_payment(event)

examples/idempotency/src/working_with_custom_idempotency_key_prefix_standalone.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -29,15 +29,15 @@ class Order:
2929
data_keyword_argument="order",
3030
config=config,
3131
persistence_store=dynamodb,
32-
key_prefix="my_custom_prefix", # (1)!
32+
key_prefix="my_custom_prefix", # (1)!
3333
)
34-
def process_order(order: Order):
34+
def process_order(order: Order):
3535
return f"processed order {order.order_id}"
3636

3737

3838
def lambda_handler(event: dict, context: LambdaContext):
3939
# see Lambda timeouts section
40-
config.register_lambda_context(context)
40+
config.register_lambda_context(context)
4141

4242
order_item = OrderItem(sku="fake", description="sample")
4343
order = Order(item=order_item, order_id=1)

examples/jmespath_functions/src/powertools_json_idempotency_jmespath.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,7 @@
1616
config = IdempotencyConfig(event_key_jmespath="powertools_json(body)")
1717

1818

19-
class PaymentError(Exception):
20-
...
19+
class PaymentError(Exception): ...
2120

2221

2322
@idempotent(config=config, persistence_store=persistence_layer)

examples/logger/src/append_keys_vs_extra.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@
88
logger = Logger(service="payment")
99

1010

11-
class PaymentError(Exception):
12-
...
11+
class PaymentError(Exception): ...
1312

1413

1514
def lambda_handler(event, context):

0 commit comments

Comments
 (0)