id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
5,403 | from typing import List
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import AppSyncResolver
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.shared.types import TypedDict
from aws_lambda_powertools.utilities.data_classes.appsync import scalar_types_utils
from aws_lambda_powertools.utilities.typing import LambdaContext
class Location(TypedDict, total=False):
id: str # noqa AA03 VNE003, required due to GraphQL Schema
name: str
description: str
address: str
commonField: str
def list_locations(page: int = 0, size: int = 10) -> List[Location]:
return [{"id": scalar_types_utils.make_id(), "name": "Smooth Grooves"}] | null |
5,404 | from typing import List
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import AppSyncResolver
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.shared.types import TypedDict
from aws_lambda_powertools.utilities.data_classes.appsync import scalar_types_utils
from aws_lambda_powertools.utilities.typing import LambdaContext
def common_field() -> str:
# Would match all fieldNames matching 'commonField'
return scalar_types_utils.make_id() | null |
5,405 | from typing import List
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import AppSyncResolver
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.shared.types import TypedDict
from aws_lambda_powertools.utilities.data_classes.appsync import scalar_types_utils
from aws_lambda_powertools.utilities.typing import LambdaContext
app = AppSyncResolver()
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return app.resolve(event, context) | null |
5,406 | from __future__ import annotations
import json
from dataclasses import dataclass
from pathlib import Path
import pytest
from assert_graphql_response_module import Location, app
def lambda_context():
@dataclass
class LambdaContext:
function_name: str = "test"
memory_limit_in_mb: int = 128
invoked_function_arn: str = "arn:aws:lambda:eu-west-1:123456789012:function:test"
aws_request_id: str = "da658bd3-2d6f-4e7b-8ec2-937234644fdc"
return LambdaContext() | null |
5,407 | from __future__ import annotations
import json
from dataclasses import dataclass
from pathlib import Path
import pytest
from assert_graphql_response_module import Location, app
app = AppSyncResolver()
class Location(TypedDict, total=False):
def test_direct_resolver(lambda_context):
# GIVEN
fake_event = json.loads(Path("assert_graphql_response.json").read_text())
# WHEN
result: list[Location] = app(fake_event, lambda_context)
# THEN
assert result[0]["name"] == "Perkins-Reed" | null |
5,408 | from typing import List
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import AppSyncResolver
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.shared.types import TypedDict
from aws_lambda_powertools.utilities.data_classes.appsync import scalar_types_utils
from aws_lambda_powertools.utilities.typing import LambdaContext
class Merchant(TypedDict, total=False):
id: str # noqa AA03 VNE003, required due to GraphQL Schema
name: str
description: str
commonField: str
def find_merchant(search: str) -> List[Merchant]:
merchants: List[Merchant] = [
{
"id": scalar_types_utils.make_id(),
"name": "Parry-Wood",
"description": "Possimus doloremque tempora harum deleniti eum.",
},
{
"id": scalar_types_utils.make_id(),
"name": "Shaw, Owen and Jones",
"description": "Aliquam iste architecto suscipit in.",
},
]
return [merchant for merchant in merchants if search == merchant["name"]] | null |
5,410 | import asyncio
from typing import List
import aiohttp
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import AppSyncResolver
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.shared.types import TypedDict
from aws_lambda_powertools.tracing import aiohttp_trace_config
from aws_lambda_powertools.utilities.typing import LambdaContext
class Todo(TypedDict, total=False):
id: str # noqa AA03 VNE003, required due to GraphQL Schema
userId: str
title: str
completed: bool
async def list_todos() -> List[Todo]:
async with aiohttp.ClientSession(trace_configs=[aiohttp_trace_config()]) as session:
async with session.get("https://jsonplaceholder.typicode.com/todos") as resp:
result: List[Todo] = await resp.json()
return result[:2] # first two results to demo assertion | null |
5,412 | from typing import List
import requests
from requests import Response
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import AppSyncResolver
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.shared.types import TypedDict
from aws_lambda_powertools.utilities.data_classes.appsync import scalar_types_utils
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger()
class Todo(TypedDict, total=False):
id: str # noqa AA03 VNE003, required due to GraphQL Schema
userId: str
title: str
completed: bool
def get_todo(
id: str = "", # noqa AA03 VNE003 shadows built-in id to match query argument, e.g., getTodo(id: "some_id")
) -> Todo:
logger.info(f"Fetching Todo {id}")
todos: Response = requests.get(f"https://jsonplaceholder.typicode.com/todos/{id}")
todos.raise_for_status()
return todos.json() | null |
5,413 | from typing import List
import requests
from requests import Response
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import AppSyncResolver
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.shared.types import TypedDict
from aws_lambda_powertools.utilities.data_classes.appsync import scalar_types_utils
from aws_lambda_powertools.utilities.typing import LambdaContext
class Todo(TypedDict, total=False):
id: str # noqa AA03 VNE003, required due to GraphQL Schema
userId: str
title: str
completed: bool
def list_todos() -> List[Todo]:
todos: Response = requests.get("https://jsonplaceholder.typicode.com/todos")
todos.raise_for_status()
# for brevity, we'll limit to the first 10 only
return todos.json()[:10] | null |
5,414 | from typing import List
import requests
from requests import Response
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import AppSyncResolver
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.shared.types import TypedDict
from aws_lambda_powertools.utilities.data_classes.appsync import scalar_types_utils
from aws_lambda_powertools.utilities.typing import LambdaContext
class Todo(TypedDict, total=False):
def create_todo(title: str) -> Todo:
payload = {"userId": scalar_types_utils.make_id(), "title": title, "completed": False} # dummy UUID str
todo: Response = requests.post("https://jsonplaceholder.typicode.com/todos", json=payload)
todo.raise_for_status()
return todo.json() | null |
5,415 | from typing import List
import requests
from requests import Response
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import AppSyncResolver
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.shared.types import TypedDict
from aws_lambda_powertools.utilities.data_classes.appsync import scalar_types_utils
from aws_lambda_powertools.utilities.typing import LambdaContext
app = AppSyncResolver()
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return app.resolve(event, context) | null |
5,416 | from typing import List
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import AppSyncResolver
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.shared.types import TypedDict
from aws_lambda_powertools.utilities.data_classes.appsync import scalar_types_utils
from aws_lambda_powertools.utilities.data_classes.appsync_resolver_event import (
AppSyncResolverEvent,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger()
app = AppSyncResolver()
class Location(TypedDict, total=False):
def list_locations(page: int = 0, size: int = 10) -> List[Location]:
# additional properties/methods will now be available under current_event
logger.debug(f"Request country origin: {app.current_event.country_viewer}") # type: ignore[attr-defined]
return [{"id": scalar_types_utils.make_id(), "name": "Perry, James and Carroll"}] | null |
5,417 | from typing import List
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import AppSyncResolver
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.shared.types import TypedDict
from aws_lambda_powertools.utilities.data_classes.appsync import scalar_types_utils
from aws_lambda_powertools.utilities.data_classes.appsync_resolver_event import (
AppSyncResolverEvent,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
app = AppSyncResolver()
class MyCustomModel(AppSyncResolverEvent):
def country_viewer(self) -> str:
return self.get_header_value(name="cloudfront-viewer-country", default_value="", case_sensitive=False) # type: ignore[return-value] # sentinel typing # noqa: E501
def api_key(self) -> str:
return self.get_header_value(name="x-api-key", default_value="", case_sensitive=False) # type: ignore[return-value] # sentinel typing # noqa: E501
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return app.resolve(event, context, data_model=MyCustomModel) | null |
5,418 | import requests
from typing_extensions import Annotated
from aws_lambda_powertools.event_handler import BedrockAgentResolver
from aws_lambda_powertools.event_handler.openapi.params import Body, Path
from aws_lambda_powertools.utilities.typing import LambdaContext
description="Loads a TODO item identified by the `todo_id`",
class Path(Param):
"""
A class used internally to represent a path parameter in a path operation.
"""
in_ = ParamTypes.path
def __init__(
self,
default: Any = ...,
*,
default_factory: Union[Callable[[], Any], None] = _Unset,
annotation: Optional[Any] = None,
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
# MAINTENANCE: update when deprecating Pydantic v1, import these types
# MAINTENANCE: validation_alias: str | AliasPath | AliasChoices | None
validation_alias: Union[str, None] = None,
serialization_alias: Union[str, None] = None,
title: Optional[str] = None,
description: Optional[str] = None,
gt: Optional[float] = None,
ge: Optional[float] = None,
lt: Optional[float] = None,
le: Optional[float] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
pattern: Optional[str] = None,
discriminator: Union[str, None] = None,
strict: Union[bool, None] = _Unset,
multiple_of: Union[float, None] = _Unset,
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
examples: Optional[List[Any]] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
):
"""
Constructs a new Path param.
Parameters
----------
default: Any
The default value of the parameter
default_factory: Callable[[], Any], optional
Callable that will be called when a default value is needed for this field
annotation: Any, optional
The type annotation of the parameter
alias: str, optional
The public name of the field
alias_priority: int, optional
Priority of the alias. This affects whether an alias generator is used
validation_alias: str | AliasPath | AliasChoices | None, optional
Alias to be used for validation only
serialization_alias: str | AliasPath | AliasChoices | None, optional
Alias to be used for serialization only
title: str, optional
The title of the parameter
description: str, optional
The description of the parameter
gt: float, optional
Only applies to numbers, required the field to be "greater than"
ge: float, optional
Only applies to numbers, required the field to be "greater than or equal"
lt: float, optional
Only applies to numbers, required the field to be "less than"
le: float, optional
Only applies to numbers, required the field to be "less than or equal"
min_length: int, optional
Only applies to strings, required the field to have a minimum length
max_length: int, optional
Only applies to strings, required the field to have a maximum length
pattern: str, optional
Only applies to strings, requires the field match against a regular expression pattern string
discriminator: str, optional
Parameter field name for discriminating the type in a tagged union
strict: bool, optional
Enables Pydantic's strict mode for the field
multiple_of: float, optional
Only applies to numbers, requires the field to be a multiple of the given value
allow_inf_nan: bool, optional
Only applies to numbers, requires the field to allow infinity and NaN values
max_digits: int, optional
Only applies to Decimals, requires the field to have a maxmium number of digits within the decimal.
decimal_places: int, optional
Only applies to Decimals, requires the field to have at most a number of decimal places
examples: List[Any], optional
A list of examples for the parameter
deprecated: bool, optional
If `True`, the parameter will be marked as deprecated
include_in_schema: bool, optional
If `False`, the parameter will be excluded from the generated OpenAPI schema
json_schema_extra: Dict[str, Any], optional
Extra values to include in the generated OpenAPI schema
"""
if default is not ...:
raise AssertionError("Path parameters cannot have a default value")
super(Path, self).__init__(
default=default,
default_factory=default_factory,
annotation=annotation,
alias=alias,
alias_priority=alias_priority,
validation_alias=validation_alias,
serialization_alias=serialization_alias,
title=title,
description=description,
gt=gt,
ge=ge,
lt=lt,
le=le,
min_length=min_length,
max_length=max_length,
pattern=pattern,
discriminator=discriminator,
strict=strict,
multiple_of=multiple_of,
allow_inf_nan=allow_inf_nan,
max_digits=max_digits,
decimal_places=decimal_places,
deprecated=deprecated,
examples=examples,
include_in_schema=include_in_schema,
json_schema_extra=json_schema_extra,
**extra,
)
class Body(FieldInfo):
"""
A class used internally to represent a body parameter in a path operation.
"""
def __init__(
self,
default: Any = Undefined,
*,
default_factory: Union[Callable[[], Any], None] = _Unset,
annotation: Optional[Any] = None,
embed: bool = False,
media_type: str = "application/json",
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
# MAINTENANCE: update when deprecating Pydantic v1, import these types
# str | AliasPath | AliasChoices | None
validation_alias: Union[str, None] = None,
serialization_alias: Union[str, None] = None,
title: Optional[str] = None,
description: Optional[str] = None,
gt: Optional[float] = None,
ge: Optional[float] = None,
lt: Optional[float] = None,
le: Optional[float] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
pattern: Optional[str] = None,
discriminator: Union[str, None] = None,
strict: Union[bool, None] = _Unset,
multiple_of: Union[float, None] = _Unset,
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
examples: Optional[List[Any]] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
):
self.embed = embed
self.media_type = media_type
self.deprecated = deprecated
self.include_in_schema = include_in_schema
kwargs = dict(
default=default,
default_factory=default_factory,
alias=alias,
title=title,
description=description,
gt=gt,
ge=ge,
lt=lt,
le=le,
min_length=min_length,
max_length=max_length,
discriminator=discriminator,
multiple_of=multiple_of,
allow_nan=allow_inf_nan,
max_digits=max_digits,
decimal_places=decimal_places,
**extra,
)
if examples is not None:
kwargs["examples"] = examples
current_json_schema_extra = json_schema_extra or extra
if PYDANTIC_V2:
kwargs.update(
{
"annotation": annotation,
"alias_priority": alias_priority,
"validation_alias": validation_alias,
"serialization_alias": serialization_alias,
"strict": strict,
"json_schema_extra": current_json_schema_extra,
"pattern": pattern,
},
)
else:
kwargs["regex"] = pattern
kwargs.update(**current_json_schema_extra)
use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}
super().__init__(**use_kwargs)
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.default})"
def get_todo_title(
todo_id: Annotated[int, Path(description="The ID of the TODO item from which to retrieve the title")],
) -> Annotated[str, Body(description="The TODO title")]:
todo = requests.get(f"https://jsonplaceholder.typicode.com/todos/{todo_id}")
todo.raise_for_status()
return todo.json()["title"] | null |
5,419 | import requests
from typing_extensions import Annotated
from aws_lambda_powertools.event_handler import BedrockAgentResolver
from aws_lambda_powertools.event_handler.openapi.params import Body, Path
from aws_lambda_powertools.utilities.typing import LambdaContext
app = BedrockAgentResolver()
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return app.resolve(event, context) | null |
5,420 | import requests
from aws_lambda_powertools.event_handler import BedrockAgentResolver
from aws_lambda_powertools.event_handler.openapi.models import Contact, Server
from aws_lambda_powertools.utilities.typing import LambdaContext
def get_todo_title(todo_id: int) -> str:
todo = requests.get(f"https://jsonplaceholder.typicode.com/todos/{todo_id}")
todo.raise_for_status()
return todo.json()["title"] | null |
5,421 | import requests
from aws_lambda_powertools.event_handler import BedrockAgentResolver
from aws_lambda_powertools.event_handler.openapi.models import Contact, Server
from aws_lambda_powertools.utilities.typing import LambdaContext
app = BedrockAgentResolver()
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return app.resolve(event, context) | null |
5,422 | from dataclasses import dataclass
import assert_bedrock_agent_response_module
import pytest
def lambda_context():
@dataclass
class LambdaContext:
function_name: str = "test"
memory_limit_in_mb: int = 128
invoked_function_arn: str = "arn:aws:lambda:eu-west-1:123456789012:function:test"
aws_request_id: str = "da658bd3-2d6f-4e7b-8ec2-937234644fdc"
return LambdaContext() | null |
5,423 | from dataclasses import dataclass
import assert_bedrock_agent_response_module
import pytest
def test_lambda_handler(lambda_context):
minimal_event = {
"apiPath": "/current_time",
"httpMethod": "GET",
"inputText": "What is the current time?",
}
# Example of Bedrock Agent API request event:
# https://docs.aws.amazon.com/bedrock/latest/userguide/agents-lambda.html#agents-lambda-input
ret = assert_bedrock_agent_response_module.lambda_handler(minimal_event, lambda_context)
assert ret["response"]["httpStatuScode"] == 200
assert ret["response"]["responseBody"]["application/json"]["body"] != "" | null |
5,424 | from time import time
from aws_lambda_powertools import Logger
from aws_lambda_powertools.event_handler import BedrockAgentResolver
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger()
app = BedrockAgentResolver()
def current_time() -> int:
logger.append_keys(
session_id=app.current_event.session_id,
action_group=app.current_event.action_group,
input_text=app.current_event.input_text,
)
logger.info("Serving current_time")
return int(time()) | null |
5,425 | from time import time
from aws_lambda_powertools import Logger
from aws_lambda_powertools.event_handler import BedrockAgentResolver
from aws_lambda_powertools.utilities.typing import LambdaContext
app = BedrockAgentResolver()
def lambda_handler(event: dict, context: LambdaContext):
return app.resolve(event, context) | null |
5,426 | from time import time
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import BedrockAgentResolver
from aws_lambda_powertools.utilities.typing import LambdaContext
def current_time() -> int:
return int(time()) | null |
5,427 | from time import time
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import BedrockAgentResolver
from aws_lambda_powertools.utilities.typing import LambdaContext
app = BedrockAgentResolver()
def lambda_handler(event: dict, context: LambdaContext):
return app.resolve(event, context) | null |
5,428 | import requests
from typing_extensions import Annotated
from aws_lambda_powertools import Logger
from aws_lambda_powertools.event_handler import BedrockAgentResolver
from aws_lambda_powertools.event_handler.openapi.params import Body, Query
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger()
description="Creates a TODO",
class Query(Param):
"""
A class used internally to represent a query parameter in a path operation.
"""
in_ = ParamTypes.query
def __init__(
self,
default: Any = _Unset,
*,
default_factory: Union[Callable[[], Any], None] = _Unset,
annotation: Optional[Any] = None,
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
validation_alias: Union[str, None] = None,
serialization_alias: Union[str, None] = None,
title: Optional[str] = None,
description: Optional[str] = None,
gt: Optional[float] = None,
ge: Optional[float] = None,
lt: Optional[float] = None,
le: Optional[float] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
pattern: Optional[str] = None,
discriminator: Union[str, None] = None,
strict: Union[bool, None] = _Unset,
multiple_of: Union[float, None] = _Unset,
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
examples: Optional[List[Any]] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
):
"""
Constructs a new Query param.
Parameters
----------
default: Any
The default value of the parameter
default_factory: Callable[[], Any], optional
Callable that will be called when a default value is needed for this field
annotation: Any, optional
The type annotation of the parameter
alias: str, optional
The public name of the field
alias_priority: int, optional
Priority of the alias. This affects whether an alias generator is used
validation_alias: str | AliasPath | AliasChoices | None, optional
Alias to be used for validation only
serialization_alias: str | AliasPath | AliasChoices | None, optional
Alias to be used for serialization only
title: str, optional
The title of the parameter
description: str, optional
The description of the parameter
gt: float, optional
Only applies to numbers, required the field to be "greater than"
ge: float, optional
Only applies to numbers, required the field to be "greater than or equal"
lt: float, optional
Only applies to numbers, required the field to be "less than"
le: float, optional
Only applies to numbers, required the field to be "less than or equal"
min_length: int, optional
Only applies to strings, required the field to have a minimum length
max_length: int, optional
Only applies to strings, required the field to have a maximum length
pattern: str, optional
Only applies to strings, requires the field match against a regular expression pattern string
discriminator: str, optional
Parameter field name for discriminating the type in a tagged union
strict: bool, optional
Enables Pydantic's strict mode for the field
multiple_of: float, optional
Only applies to numbers, requires the field to be a multiple of the given value
allow_inf_nan: bool, optional
Only applies to numbers, requires the field to allow infinity and NaN values
max_digits: int, optional
Only applies to Decimals, requires the field to have a maxmium number of digits within the decimal.
decimal_places: int, optional
Only applies to Decimals, requires the field to have at most a number of decimal places
examples: List[Any], optional
A list of examples for the parameter
deprecated: bool, optional
If `True`, the parameter will be marked as deprecated
include_in_schema: bool, optional
If `False`, the parameter will be excluded from the generated OpenAPI schema
json_schema_extra: Dict[str, Any], optional
Extra values to include in the generated OpenAPI schema
"""
super().__init__(
default=default,
default_factory=default_factory,
annotation=annotation,
alias=alias,
alias_priority=alias_priority,
validation_alias=validation_alias,
serialization_alias=serialization_alias,
title=title,
description=description,
gt=gt,
ge=ge,
lt=lt,
le=le,
min_length=min_length,
max_length=max_length,
pattern=pattern,
discriminator=discriminator,
strict=strict,
multiple_of=multiple_of,
allow_inf_nan=allow_inf_nan,
max_digits=max_digits,
decimal_places=decimal_places,
deprecated=deprecated,
examples=examples,
include_in_schema=include_in_schema,
json_schema_extra=json_schema_extra,
**extra,
)
class Body(FieldInfo):
"""
A class used internally to represent a body parameter in a path operation.
"""
def __init__(
self,
default: Any = Undefined,
*,
default_factory: Union[Callable[[], Any], None] = _Unset,
annotation: Optional[Any] = None,
embed: bool = False,
media_type: str = "application/json",
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
# MAINTENANCE: update when deprecating Pydantic v1, import these types
# str | AliasPath | AliasChoices | None
validation_alias: Union[str, None] = None,
serialization_alias: Union[str, None] = None,
title: Optional[str] = None,
description: Optional[str] = None,
gt: Optional[float] = None,
ge: Optional[float] = None,
lt: Optional[float] = None,
le: Optional[float] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
pattern: Optional[str] = None,
discriminator: Union[str, None] = None,
strict: Union[bool, None] = _Unset,
multiple_of: Union[float, None] = _Unset,
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
examples: Optional[List[Any]] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
):
self.embed = embed
self.media_type = media_type
self.deprecated = deprecated
self.include_in_schema = include_in_schema
kwargs = dict(
default=default,
default_factory=default_factory,
alias=alias,
title=title,
description=description,
gt=gt,
ge=ge,
lt=lt,
le=le,
min_length=min_length,
max_length=max_length,
discriminator=discriminator,
multiple_of=multiple_of,
allow_nan=allow_inf_nan,
max_digits=max_digits,
decimal_places=decimal_places,
**extra,
)
if examples is not None:
kwargs["examples"] = examples
current_json_schema_extra = json_schema_extra or extra
if PYDANTIC_V2:
kwargs.update(
{
"annotation": annotation,
"alias_priority": alias_priority,
"validation_alias": validation_alias,
"serialization_alias": serialization_alias,
"strict": strict,
"json_schema_extra": current_json_schema_extra,
"pattern": pattern,
},
)
else:
kwargs["regex"] = pattern
kwargs.update(**current_json_schema_extra)
use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}
super().__init__(**use_kwargs)
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.default})"
def create_todo(
title: Annotated[str, Query(max_length=200, strict=True, description="The TODO title")], # (1)!
) -> Annotated[bool, Body(description="Was the TODO created correctly?")]:
todo = requests.post("https://jsonplaceholder.typicode.com/todos", data={"title": title})
try:
todo.raise_for_status()
return True
except Exception:
logger.exception("Error creating TODO")
return False | null |
5,429 | import requests
from typing_extensions import Annotated
from aws_lambda_powertools import Logger
from aws_lambda_powertools.event_handler import BedrockAgentResolver
from aws_lambda_powertools.event_handler.openapi.params import Body, Query
from aws_lambda_powertools.utilities.typing import LambdaContext
app = BedrockAgentResolver()
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return app.resolve(event, context) | null |
5,430 | import time
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import BedrockAgentResolver
from aws_lambda_powertools.event_handler.openapi.params import Body
from aws_lambda_powertools.shared.types import Annotated
from aws_lambda_powertools.utilities.typing import LambdaContext
class Body(FieldInfo):
"""
A class used internally to represent a body parameter in a path operation.
"""
def __init__(
self,
default: Any = Undefined,
*,
default_factory: Union[Callable[[], Any], None] = _Unset,
annotation: Optional[Any] = None,
embed: bool = False,
media_type: str = "application/json",
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
# MAINTENANCE: update when deprecating Pydantic v1, import these types
# str | AliasPath | AliasChoices | None
validation_alias: Union[str, None] = None,
serialization_alias: Union[str, None] = None,
title: Optional[str] = None,
description: Optional[str] = None,
gt: Optional[float] = None,
ge: Optional[float] = None,
lt: Optional[float] = None,
le: Optional[float] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
pattern: Optional[str] = None,
discriminator: Union[str, None] = None,
strict: Union[bool, None] = _Unset,
multiple_of: Union[float, None] = _Unset,
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
examples: Optional[List[Any]] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
):
self.embed = embed
self.media_type = media_type
self.deprecated = deprecated
self.include_in_schema = include_in_schema
kwargs = dict(
default=default,
default_factory=default_factory,
alias=alias,
title=title,
description=description,
gt=gt,
ge=ge,
lt=lt,
le=le,
min_length=min_length,
max_length=max_length,
discriminator=discriminator,
multiple_of=multiple_of,
allow_nan=allow_inf_nan,
max_digits=max_digits,
decimal_places=decimal_places,
**extra,
)
if examples is not None:
kwargs["examples"] = examples
current_json_schema_extra = json_schema_extra or extra
if PYDANTIC_V2:
kwargs.update(
{
"annotation": annotation,
"alias_priority": alias_priority,
"validation_alias": validation_alias,
"serialization_alias": serialization_alias,
"strict": strict,
"json_schema_extra": current_json_schema_extra,
"pattern": pattern,
},
)
else:
kwargs["regex"] = pattern
kwargs.update(**current_json_schema_extra)
use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}
super().__init__(**use_kwargs)
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.default})"
def current_time() -> Annotated[int, Body(description="Current time in milliseconds")]:
return round(time.time() * 1000) | null |
5,431 | from pydantic import EmailStr
from typing_extensions import Annotated
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import BedrockAgentResolver
from aws_lambda_powertools.event_handler.openapi.params import Body, Query
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger()
class Query(Param):
"""
A class used internally to represent a query parameter in a path operation.
"""
in_ = ParamTypes.query
def __init__(
self,
default: Any = _Unset,
*,
default_factory: Union[Callable[[], Any], None] = _Unset,
annotation: Optional[Any] = None,
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
validation_alias: Union[str, None] = None,
serialization_alias: Union[str, None] = None,
title: Optional[str] = None,
description: Optional[str] = None,
gt: Optional[float] = None,
ge: Optional[float] = None,
lt: Optional[float] = None,
le: Optional[float] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
pattern: Optional[str] = None,
discriminator: Union[str, None] = None,
strict: Union[bool, None] = _Unset,
multiple_of: Union[float, None] = _Unset,
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
examples: Optional[List[Any]] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
):
"""
Constructs a new Query param.
Parameters
----------
default: Any
The default value of the parameter
default_factory: Callable[[], Any], optional
Callable that will be called when a default value is needed for this field
annotation: Any, optional
The type annotation of the parameter
alias: str, optional
The public name of the field
alias_priority: int, optional
Priority of the alias. This affects whether an alias generator is used
validation_alias: str | AliasPath | AliasChoices | None, optional
Alias to be used for validation only
serialization_alias: str | AliasPath | AliasChoices | None, optional
Alias to be used for serialization only
title: str, optional
The title of the parameter
description: str, optional
The description of the parameter
gt: float, optional
Only applies to numbers, required the field to be "greater than"
ge: float, optional
Only applies to numbers, required the field to be "greater than or equal"
lt: float, optional
Only applies to numbers, required the field to be "less than"
le: float, optional
Only applies to numbers, required the field to be "less than or equal"
min_length: int, optional
Only applies to strings, required the field to have a minimum length
max_length: int, optional
Only applies to strings, required the field to have a maximum length
pattern: str, optional
Only applies to strings, requires the field match against a regular expression pattern string
discriminator: str, optional
Parameter field name for discriminating the type in a tagged union
strict: bool, optional
Enables Pydantic's strict mode for the field
multiple_of: float, optional
Only applies to numbers, requires the field to be a multiple of the given value
allow_inf_nan: bool, optional
Only applies to numbers, requires the field to allow infinity and NaN values
max_digits: int, optional
Only applies to Decimals, requires the field to have a maxmium number of digits within the decimal.
decimal_places: int, optional
Only applies to Decimals, requires the field to have at most a number of decimal places
examples: List[Any], optional
A list of examples for the parameter
deprecated: bool, optional
If `True`, the parameter will be marked as deprecated
include_in_schema: bool, optional
If `False`, the parameter will be excluded from the generated OpenAPI schema
json_schema_extra: Dict[str, Any], optional
Extra values to include in the generated OpenAPI schema
"""
super().__init__(
default=default,
default_factory=default_factory,
annotation=annotation,
alias=alias,
alias_priority=alias_priority,
validation_alias=validation_alias,
serialization_alias=serialization_alias,
title=title,
description=description,
gt=gt,
ge=ge,
lt=lt,
le=le,
min_length=min_length,
max_length=max_length,
pattern=pattern,
discriminator=discriminator,
strict=strict,
multiple_of=multiple_of,
allow_inf_nan=allow_inf_nan,
max_digits=max_digits,
decimal_places=decimal_places,
deprecated=deprecated,
examples=examples,
include_in_schema=include_in_schema,
json_schema_extra=json_schema_extra,
**extra,
)
class Body(FieldInfo):
"""
A class used internally to represent a body parameter in a path operation.
"""
def __init__(
self,
default: Any = Undefined,
*,
default_factory: Union[Callable[[], Any], None] = _Unset,
annotation: Optional[Any] = None,
embed: bool = False,
media_type: str = "application/json",
alias: Optional[str] = None,
alias_priority: Union[int, None] = _Unset,
# MAINTENANCE: update when deprecating Pydantic v1, import these types
# str | AliasPath | AliasChoices | None
validation_alias: Union[str, None] = None,
serialization_alias: Union[str, None] = None,
title: Optional[str] = None,
description: Optional[str] = None,
gt: Optional[float] = None,
ge: Optional[float] = None,
lt: Optional[float] = None,
le: Optional[float] = None,
min_length: Optional[int] = None,
max_length: Optional[int] = None,
pattern: Optional[str] = None,
discriminator: Union[str, None] = None,
strict: Union[bool, None] = _Unset,
multiple_of: Union[float, None] = _Unset,
allow_inf_nan: Union[bool, None] = _Unset,
max_digits: Union[int, None] = _Unset,
decimal_places: Union[int, None] = _Unset,
examples: Optional[List[Any]] = None,
deprecated: Optional[bool] = None,
include_in_schema: bool = True,
json_schema_extra: Union[Dict[str, Any], None] = None,
**extra: Any,
):
self.embed = embed
self.media_type = media_type
self.deprecated = deprecated
self.include_in_schema = include_in_schema
kwargs = dict(
default=default,
default_factory=default_factory,
alias=alias,
title=title,
description=description,
gt=gt,
ge=ge,
lt=lt,
le=le,
min_length=min_length,
max_length=max_length,
discriminator=discriminator,
multiple_of=multiple_of,
allow_nan=allow_inf_nan,
max_digits=max_digits,
decimal_places=decimal_places,
**extra,
)
if examples is not None:
kwargs["examples"] = examples
current_json_schema_extra = json_schema_extra or extra
if PYDANTIC_V2:
kwargs.update(
{
"annotation": annotation,
"alias_priority": alias_priority,
"validation_alias": validation_alias,
"serialization_alias": serialization_alias,
"strict": strict,
"json_schema_extra": current_json_schema_extra,
"pattern": pattern,
},
)
else:
kwargs["regex"] = pattern
kwargs.update(**current_json_schema_extra)
use_kwargs = {k: v for k, v in kwargs.items() if v is not _Unset}
super().__init__(**use_kwargs)
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.default})"
def schedule_meeting(
email: Annotated[EmailStr, Query(description="The email address of the customer")], # (2)!
) -> Annotated[bool, Body(description="Whether the meeting was scheduled successfully")]: # (3)!
logger.info("Scheduling a meeting", email=email)
return True | null |
5,432 | from pydantic import EmailStr
from typing_extensions import Annotated
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import BedrockAgentResolver
from aws_lambda_powertools.event_handler.openapi.params import Body, Query
from aws_lambda_powertools.utilities.typing import LambdaContext
app = BedrockAgentResolver()
def lambda_handler(event: dict, context: LambdaContext):
return app.resolve(event, context) | null |
5,434 | from time import time
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler import BedrockAgentResolver
from aws_lambda_powertools.utilities.typing import LambdaContext
app = BedrockAgentResolver()
def lambda_handler(event: dict, context: LambdaContext):
return app.resolve(event, context) # (2)! | null |
5,435 | from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import BatchProcessor, EventType
from aws_lambda_powertools.utilities.data_classes.kinesis_stream_event import (
KinesisStreamRecord,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.KinesisDataStreams)
logger = Logger()
def record_handler(record: KinesisStreamRecord):
logger.info(record.kinesis.data_as_text)
payload: dict = record.kinesis.data_as_json()
logger.info(payload)
def lambda_handler(event, context: LambdaContext):
batch = event["Records"]
with processor(records=batch, handler=record_handler):
processed_messages = processor.process() # kick off processing, return list[tuple]
logger.info(f"Processed ${len(processed_messages)} messages")
return processor.response() | null |
5,436 | from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
batch_processor,
)
from aws_lambda_powertools.utilities.data_classes.kinesis_stream_event import (
KinesisStreamRecord,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger()
class KinesisStreamRecord(DictWrapper):
def aws_region(self) -> str:
def event_id(self) -> str:
def event_name(self) -> str:
def event_source(self) -> str:
def event_source_arn(self) -> str:
def event_version(self) -> str:
def invoke_identity_arn(self) -> str:
def kinesis(self) -> KinesisStreamRecordPayload:
def record_handler(record: KinesisStreamRecord):
logger.info(record.kinesis.data_as_text)
payload: dict = record.kinesis.data_as_json()
logger.info(payload) | null |
5,437 | from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
batch_processor,
)
from aws_lambda_powertools.utilities.data_classes.kinesis_stream_event import (
KinesisStreamRecord,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.KinesisDataStreams)
def lambda_handler(event, context: LambdaContext):
return processor.response() | null |
5,438 | from __future__ import annotations
import json
from typing import List, Tuple
from typing_extensions import Literal
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import BatchProcessor, EventType
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.SQS)
logger = Logger()
def record_handler(record: SQSRecord):
payload: str = record.body
if payload:
item: dict = json.loads(payload)
logger.info(item)
class SQSRecord(DictWrapper):
"""An Amazon SQS message"""
NestedEvent = TypeVar("NestedEvent", bound=DictWrapper)
def message_id(self) -> str:
"""A unique identifier for the message.
A messageId is considered unique across all AWS accounts for an extended period of time."""
return self["messageId"]
def receipt_handle(self) -> str:
"""An identifier associated with the act of receiving the message.
A new receipt handle is returned every time you receive a message. When deleting a message,
you provide the last received receipt handle to delete the message."""
return self["receiptHandle"]
def body(self) -> str:
"""The message's contents (not URL-encoded)."""
return self["body"]
def json_body(self) -> Any:
"""Deserializes JSON string available in 'body' property
Notes
-----
**Strict typing**
Caller controls the type as we can't use recursive generics here.
JSON Union types would force caller to have to cast a type. Instead,
we choose Any to ease ergonomics and other tools receiving this data.
Examples
--------
**Type deserialized data from JSON string**
```python
data: dict = record.json_body # {"telemetry": [], ...}
# or
data: list = record.json_body # ["telemetry_values"]
```
"""
return self._json_deserializer(self["body"])
def attributes(self) -> SQSRecordAttributes:
"""A map of the attributes requested in ReceiveMessage to their respective values."""
return SQSRecordAttributes(self["attributes"])
def message_attributes(self) -> SQSMessageAttributes:
"""Each message attribute consists of a Name, Type, and Value."""
return SQSMessageAttributes(self["messageAttributes"])
def md5_of_body(self) -> str:
"""An MD5 digest of the non-URL-encoded message body string."""
return self["md5OfBody"]
def event_source(self) -> str:
"""The AWS service from which the SQS record originated. For SQS, this is `aws:sqs`"""
return self["eventSource"]
def event_source_arn(self) -> str:
"""The Amazon Resource Name (ARN) of the event source"""
return self["eventSourceARN"]
def aws_region(self) -> str:
"""aws region eg: us-east-1"""
return self["awsRegion"]
def queue_url(self) -> str:
"""The URL of the queue."""
arn_parts = self["eventSourceARN"].split(":")
region = arn_parts[3]
account_id = arn_parts[4]
queue_name = arn_parts[5]
queue_url = f"https://sqs.{region}.amazonaws.com/{account_id}/{queue_name}"
return queue_url
def decoded_nested_s3_event(self) -> S3Event:
"""Returns the nested `S3Event` object that is sent in the body of a SQS message.
Even though you can typecast the object returned by `record.json_body`
directly, this method is provided as a shortcut for convenience.
Notes
-----
This method does not validate whether the SQS message body is actually a valid S3 event.
Examples
--------
```python
nested_event: S3Event = record.decoded_nested_s3_event
```
"""
return self._decode_nested_event(S3Event)
def decoded_nested_sns_event(self) -> SNSMessage:
"""Returns the nested `SNSMessage` object that is sent in the body of a SQS message.
Even though you can typecast the object returned by `record.json_body`
directly, this method is provided as a shortcut for convenience.
Notes
-----
This method does not validate whether the SQS message body is actually
a valid SNS message.
Examples
--------
```python
nested_message: SNSMessage = record.decoded_nested_sns_event
```
"""
return self._decode_nested_event(SNSMessage)
def _decode_nested_event(self, nested_event_class: Type[NestedEvent]) -> NestedEvent:
"""Returns the nested event source data object.
This is useful for handling events that are sent in the body of a SQS message.
Examples
--------
```python
data: S3Event = self._decode_nested_event(S3Event)
```
"""
return nested_event_class(self.json_body)
def lambda_handler(event, context: LambdaContext):
batch = event["Records"] # (1)!
with processor(records=batch, handler=record_handler):
processed_messages: List[Tuple] = processor.process()
for message in processed_messages:
status: Literal["success", "fail"] = message[0]
cause: str = message[1] # (2)!
record: SQSRecord = message[2]
logger.info(status, record=record, cause=cause)
return processor.response() | null |
5,439 | import os
import sys
from random import randint
from typing import Any
import boto3
from aws_lambda_powertools import Logger
from aws_lambda_powertools.utilities.batch import (
BasePartialProcessor,
process_partial_response,
)
processor = MyPartialProcessor(table_name)
def record_handler(record):
return randint(0, 100)
def lambda_handler(event, context):
return process_partial_response(event=event, record_handler=record_handler, processor=processor, context=context) | null |
5,440 | import json
from typing import Any, Dict
from aws_lambda_powertools import Logger, Metrics, Tracer
from aws_lambda_powertools.metrics import MetricUnit
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
ExceptionInfo,
FailureResponse,
process_partial_response,
)
from aws_lambda_powertools.utilities.batch.base import SuccessResponse
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = MyProcessor(event_type=EventType.SQS)
def record_handler(record: SQSRecord):
def lambda_handler(event, context: LambdaContext):
return process_partial_response(event=event, record_handler=record_handler, processor=processor, context=context) | null |
5,441 | from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
process_partial_response,
)
from aws_lambda_powertools.utilities.parser import BaseModel
from aws_lambda_powertools.utilities.parser.models import (
KinesisDataStreamRecord,
KinesisDataStreamRecordPayload,
)
from aws_lambda_powertools.utilities.parser.types import Json
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.KinesisDataStreams, model=OrderKinesisRecord)
def record_handler(record: OrderKinesisRecord):
logger.info(record.kinesis.data.item)
return record.kinesis.data.item
def lambda_handler(event, context: LambdaContext):
return process_partial_response(event=event, record_handler=record_handler, processor=processor, context=context) | null |
5,442 | from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
SqsFifoPartialProcessor,
process_partial_response,
)
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = SqsFifoPartialProcessor()
def record_handler(record: SQSRecord):
def lambda_handler(event, context: LambdaContext):
return process_partial_response(event=event, record_handler=record_handler, processor=processor, context=context) | null |
5,443 | import json
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import SqsFifoPartialProcessor
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = SqsFifoPartialProcessor()
def record_handler(record: SQSRecord):
def lambda_handler(event, context: LambdaContext):
batch = event["Records"]
with processor(records=batch, handler=record_handler):
processor.process() # kick off processing, return List[Tuple]
return processor.response() | null |
5,444 | import json
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
batch_processor,
)
from aws_lambda_powertools.utilities.data_classes.dynamo_db_stream_event import (
DynamoDBRecord,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger()
class DynamoDBRecord(DictWrapper):
def aws_region(self) -> Optional[str]:
def dynamodb(self) -> Optional[StreamRecord]:
def event_id(self) -> Optional[str]:
def event_name(self) -> Optional[DynamoDBRecordEventName]:
def event_source(self) -> Optional[str]:
def event_source_arn(self) -> Optional[str]:
def event_version(self) -> Optional[str]:
def user_identity(self) -> Optional[dict]:
def record_handler(record: DynamoDBRecord):
if record.dynamodb and record.dynamodb.new_image:
logger.info(record.dynamodb.new_image)
message = record.dynamodb.new_image.get("Message")
if message:
payload: dict = json.loads(message)
logger.info(payload) | null |
5,445 | import json
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
batch_processor,
)
from aws_lambda_powertools.utilities.data_classes.dynamo_db_stream_event import (
DynamoDBRecord,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.DynamoDBStreams)
def lambda_handler(event, context: LambdaContext):
return processor.response() | null |
5,446 | from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
process_partial_response,
)
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.SQS)
def record_handler(record: SQSRecord):
payload: str = record.body
logger.info(payload)
if not payload:
raise InvalidPayload("Payload does not contain minimum information to be processed.") # (1)!
def lambda_handler(event, context: LambdaContext):
return process_partial_response( # (2)!
event=event,
record_handler=record_handler,
processor=processor,
context=context,
) | null |
5,447 | from typing import Optional
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import BatchProcessor, EventType
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.SQS)
def record_handler(record: SQSRecord, lambda_context: Optional[LambdaContext] = None):
if lambda_context is not None:
remaining_time = lambda_context.get_remaining_time_in_millis()
logger.info(remaining_time)
def lambda_handler(event, context: LambdaContext):
batch = event["Records"]
with processor(records=batch, handler=record_handler, lambda_context=context):
result = processor.process()
return result | null |
5,448 | import json
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import BatchProcessor, EventType
from aws_lambda_powertools.utilities.data_classes.dynamo_db_stream_event import (
DynamoDBRecord,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.DynamoDBStreams)
logger = Logger()
def record_handler(record: DynamoDBRecord):
def lambda_handler(event, context: LambdaContext):
batch = event["Records"]
with processor(records=batch, handler=record_handler):
processed_messages = processor.process() # kick off processing, return list[tuple]
logger.info(f"Processed ${len(processed_messages)} messages")
return processor.response() | null |
5,449 | import json
from typing import Dict, Optional
from typing_extensions import Literal
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
process_partial_response,
)
from aws_lambda_powertools.utilities.parser import BaseModel, validator
from aws_lambda_powertools.utilities.parser.models import (
DynamoDBStreamChangedRecordModel,
DynamoDBStreamRecordModel,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.DynamoDBStreams, model=OrderDynamoDBRecord)
def record_handler(record: OrderDynamoDBRecord):
if record.dynamodb.NewImage and record.dynamodb.NewImage.Message:
logger.info(record.dynamodb.NewImage.Message.item)
return record.dynamodb.NewImage.Message.item
def lambda_handler(event, context: LambdaContext):
return process_partial_response(event=event, record_handler=record_handler, processor=processor, context=context) | null |
5,450 | from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
process_partial_response,
)
from aws_lambda_powertools.utilities.data_classes.kinesis_stream_event import (
KinesisStreamRecord,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.KinesisDataStreams)
def record_handler(record: KinesisStreamRecord):
def lambda_handler(event, context: LambdaContext):
return process_partial_response(event=event, record_handler=record_handler, processor=processor, context=context) | null |
5,451 | from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
process_partial_response,
)
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.SQS)
def record_handler(record: SQSRecord): # (2)!
payload: str = record.json_body # if json string data, otherwise record.body for str
logger.info(payload)
def lambda_handler(event, context: LambdaContext):
return process_partial_response( # (3)!
event=event,
record_handler=record_handler,
processor=processor,
context=context,
) | null |
5,452 | from typing import Optional
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
process_partial_response,
)
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.SQS)
def record_handler(record: SQSRecord, lambda_context: Optional[LambdaContext] = None):
if lambda_context is not None:
remaining_time = lambda_context.get_remaining_time_in_millis()
logger.info(remaining_time)
def lambda_handler(event, context: LambdaContext):
return process_partial_response(event=event, record_handler=record_handler, processor=processor, context=context) | null |
5,453 | import json
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import BatchProcessor, EventType
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.SQS)
logger = Logger()
def record_handler(record: SQSRecord):
payload: str = record.body
if payload:
item: dict = json.loads(payload)
logger.info(item)
def lambda_handler(event, context: LambdaContext):
batch = event["Records"]
with processor(records=batch, handler=record_handler):
processed_messages = processor.process() # kick off processing, return list[tuple]
logger.info(f"Processed ${len(processed_messages)} messages")
return processor.response() | null |
5,454 | import json
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
process_partial_response,
)
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.SQS)
def record_handler(record: SQSRecord):
payload: str = record.body
if payload:
item: dict = json.loads(payload)
logger.info(item)
def lambda_handler(event, context: LambdaContext):
return process_partial_response(event=event, record_handler=record_handler, processor=processor, context=context) | null |
5,455 | import json
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
SqsFifoPartialProcessor,
batch_processor,
)
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger()
class SQSRecord(DictWrapper):
"""An Amazon SQS message"""
NestedEvent = TypeVar("NestedEvent", bound=DictWrapper)
def message_id(self) -> str:
"""A unique identifier for the message.
A messageId is considered unique across all AWS accounts for an extended period of time."""
return self["messageId"]
def receipt_handle(self) -> str:
"""An identifier associated with the act of receiving the message.
A new receipt handle is returned every time you receive a message. When deleting a message,
you provide the last received receipt handle to delete the message."""
return self["receiptHandle"]
def body(self) -> str:
"""The message's contents (not URL-encoded)."""
return self["body"]
def json_body(self) -> Any:
"""Deserializes JSON string available in 'body' property
Notes
-----
**Strict typing**
Caller controls the type as we can't use recursive generics here.
JSON Union types would force caller to have to cast a type. Instead,
we choose Any to ease ergonomics and other tools receiving this data.
Examples
--------
**Type deserialized data from JSON string**
```python
data: dict = record.json_body # {"telemetry": [], ...}
# or
data: list = record.json_body # ["telemetry_values"]
```
"""
return self._json_deserializer(self["body"])
def attributes(self) -> SQSRecordAttributes:
"""A map of the attributes requested in ReceiveMessage to their respective values."""
return SQSRecordAttributes(self["attributes"])
def message_attributes(self) -> SQSMessageAttributes:
"""Each message attribute consists of a Name, Type, and Value."""
return SQSMessageAttributes(self["messageAttributes"])
def md5_of_body(self) -> str:
"""An MD5 digest of the non-URL-encoded message body string."""
return self["md5OfBody"]
def event_source(self) -> str:
"""The AWS service from which the SQS record originated. For SQS, this is `aws:sqs`"""
return self["eventSource"]
def event_source_arn(self) -> str:
"""The Amazon Resource Name (ARN) of the event source"""
return self["eventSourceARN"]
def aws_region(self) -> str:
"""aws region eg: us-east-1"""
return self["awsRegion"]
def queue_url(self) -> str:
"""The URL of the queue."""
arn_parts = self["eventSourceARN"].split(":")
region = arn_parts[3]
account_id = arn_parts[4]
queue_name = arn_parts[5]
queue_url = f"https://sqs.{region}.amazonaws.com/{account_id}/{queue_name}"
return queue_url
def decoded_nested_s3_event(self) -> S3Event:
"""Returns the nested `S3Event` object that is sent in the body of a SQS message.
Even though you can typecast the object returned by `record.json_body`
directly, this method is provided as a shortcut for convenience.
Notes
-----
This method does not validate whether the SQS message body is actually a valid S3 event.
Examples
--------
```python
nested_event: S3Event = record.decoded_nested_s3_event
```
"""
return self._decode_nested_event(S3Event)
def decoded_nested_sns_event(self) -> SNSMessage:
"""Returns the nested `SNSMessage` object that is sent in the body of a SQS message.
Even though you can typecast the object returned by `record.json_body`
directly, this method is provided as a shortcut for convenience.
Notes
-----
This method does not validate whether the SQS message body is actually
a valid SNS message.
Examples
--------
```python
nested_message: SNSMessage = record.decoded_nested_sns_event
```
"""
return self._decode_nested_event(SNSMessage)
def _decode_nested_event(self, nested_event_class: Type[NestedEvent]) -> NestedEvent:
"""Returns the nested event source data object.
This is useful for handling events that are sent in the body of a SQS message.
Examples
--------
```python
data: S3Event = self._decode_nested_event(S3Event)
```
"""
return nested_event_class(self.json_body)
def record_handler(record: SQSRecord):
payload: str = record.body
if payload:
item: dict = json.loads(payload)
logger.info(item) | null |
5,456 | import json
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
SqsFifoPartialProcessor,
batch_processor,
)
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = SqsFifoPartialProcessor()
def lambda_handler(event, context: LambdaContext):
return processor.response() | null |
5,457 | from typing import Optional
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
batch_processor,
)
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger()
class SQSRecord(DictWrapper):
"""An Amazon SQS message"""
NestedEvent = TypeVar("NestedEvent", bound=DictWrapper)
def message_id(self) -> str:
"""A unique identifier for the message.
A messageId is considered unique across all AWS accounts for an extended period of time."""
return self["messageId"]
def receipt_handle(self) -> str:
"""An identifier associated with the act of receiving the message.
A new receipt handle is returned every time you receive a message. When deleting a message,
you provide the last received receipt handle to delete the message."""
return self["receiptHandle"]
def body(self) -> str:
"""The message's contents (not URL-encoded)."""
return self["body"]
def json_body(self) -> Any:
"""Deserializes JSON string available in 'body' property
Notes
-----
**Strict typing**
Caller controls the type as we can't use recursive generics here.
JSON Union types would force caller to have to cast a type. Instead,
we choose Any to ease ergonomics and other tools receiving this data.
Examples
--------
**Type deserialized data from JSON string**
```python
data: dict = record.json_body # {"telemetry": [], ...}
# or
data: list = record.json_body # ["telemetry_values"]
```
"""
return self._json_deserializer(self["body"])
def attributes(self) -> SQSRecordAttributes:
"""A map of the attributes requested in ReceiveMessage to their respective values."""
return SQSRecordAttributes(self["attributes"])
def message_attributes(self) -> SQSMessageAttributes:
"""Each message attribute consists of a Name, Type, and Value."""
return SQSMessageAttributes(self["messageAttributes"])
def md5_of_body(self) -> str:
"""An MD5 digest of the non-URL-encoded message body string."""
return self["md5OfBody"]
def event_source(self) -> str:
"""The AWS service from which the SQS record originated. For SQS, this is `aws:sqs`"""
return self["eventSource"]
def event_source_arn(self) -> str:
"""The Amazon Resource Name (ARN) of the event source"""
return self["eventSourceARN"]
def aws_region(self) -> str:
"""aws region eg: us-east-1"""
return self["awsRegion"]
def queue_url(self) -> str:
"""The URL of the queue."""
arn_parts = self["eventSourceARN"].split(":")
region = arn_parts[3]
account_id = arn_parts[4]
queue_name = arn_parts[5]
queue_url = f"https://sqs.{region}.amazonaws.com/{account_id}/{queue_name}"
return queue_url
def decoded_nested_s3_event(self) -> S3Event:
"""Returns the nested `S3Event` object that is sent in the body of a SQS message.
Even though you can typecast the object returned by `record.json_body`
directly, this method is provided as a shortcut for convenience.
Notes
-----
This method does not validate whether the SQS message body is actually a valid S3 event.
Examples
--------
```python
nested_event: S3Event = record.decoded_nested_s3_event
```
"""
return self._decode_nested_event(S3Event)
def decoded_nested_sns_event(self) -> SNSMessage:
"""Returns the nested `SNSMessage` object that is sent in the body of a SQS message.
Even though you can typecast the object returned by `record.json_body`
directly, this method is provided as a shortcut for convenience.
Notes
-----
This method does not validate whether the SQS message body is actually
a valid SNS message.
Examples
--------
```python
nested_message: SNSMessage = record.decoded_nested_sns_event
```
"""
return self._decode_nested_event(SNSMessage)
def _decode_nested_event(self, nested_event_class: Type[NestedEvent]) -> NestedEvent:
"""Returns the nested event source data object.
This is useful for handling events that are sent in the body of a SQS message.
Examples
--------
```python
data: S3Event = self._decode_nested_event(S3Event)
```
"""
return nested_event_class(self.json_body)
def record_handler(record: SQSRecord, lambda_context: Optional[LambdaContext] = None):
if lambda_context is not None:
remaining_time = lambda_context.get_remaining_time_in_millis()
logger.info(remaining_time) | null |
5,458 | from typing import Optional
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
batch_processor,
)
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.SQS)
def lambda_handler(event, context: LambdaContext):
return processor.response() | null |
5,459 | import json
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
batch_processor,
)
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger()
class SQSRecord(DictWrapper):
"""An Amazon SQS message"""
NestedEvent = TypeVar("NestedEvent", bound=DictWrapper)
def message_id(self) -> str:
"""A unique identifier for the message.
A messageId is considered unique across all AWS accounts for an extended period of time."""
return self["messageId"]
def receipt_handle(self) -> str:
"""An identifier associated with the act of receiving the message.
A new receipt handle is returned every time you receive a message. When deleting a message,
you provide the last received receipt handle to delete the message."""
return self["receiptHandle"]
def body(self) -> str:
"""The message's contents (not URL-encoded)."""
return self["body"]
def json_body(self) -> Any:
"""Deserializes JSON string available in 'body' property
Notes
-----
**Strict typing**
Caller controls the type as we can't use recursive generics here.
JSON Union types would force caller to have to cast a type. Instead,
we choose Any to ease ergonomics and other tools receiving this data.
Examples
--------
**Type deserialized data from JSON string**
```python
data: dict = record.json_body # {"telemetry": [], ...}
# or
data: list = record.json_body # ["telemetry_values"]
```
"""
return self._json_deserializer(self["body"])
def attributes(self) -> SQSRecordAttributes:
"""A map of the attributes requested in ReceiveMessage to their respective values."""
return SQSRecordAttributes(self["attributes"])
def message_attributes(self) -> SQSMessageAttributes:
"""Each message attribute consists of a Name, Type, and Value."""
return SQSMessageAttributes(self["messageAttributes"])
def md5_of_body(self) -> str:
"""An MD5 digest of the non-URL-encoded message body string."""
return self["md5OfBody"]
def event_source(self) -> str:
"""The AWS service from which the SQS record originated. For SQS, this is `aws:sqs`"""
return self["eventSource"]
def event_source_arn(self) -> str:
"""The Amazon Resource Name (ARN) of the event source"""
return self["eventSourceARN"]
def aws_region(self) -> str:
"""aws region eg: us-east-1"""
return self["awsRegion"]
def queue_url(self) -> str:
"""The URL of the queue."""
arn_parts = self["eventSourceARN"].split(":")
region = arn_parts[3]
account_id = arn_parts[4]
queue_name = arn_parts[5]
queue_url = f"https://sqs.{region}.amazonaws.com/{account_id}/{queue_name}"
return queue_url
def decoded_nested_s3_event(self) -> S3Event:
"""Returns the nested `S3Event` object that is sent in the body of a SQS message.
Even though you can typecast the object returned by `record.json_body`
directly, this method is provided as a shortcut for convenience.
Notes
-----
This method does not validate whether the SQS message body is actually a valid S3 event.
Examples
--------
```python
nested_event: S3Event = record.decoded_nested_s3_event
```
"""
return self._decode_nested_event(S3Event)
def decoded_nested_sns_event(self) -> SNSMessage:
"""Returns the nested `SNSMessage` object that is sent in the body of a SQS message.
Even though you can typecast the object returned by `record.json_body`
directly, this method is provided as a shortcut for convenience.
Notes
-----
This method does not validate whether the SQS message body is actually
a valid SNS message.
Examples
--------
```python
nested_message: SNSMessage = record.decoded_nested_sns_event
```
"""
return self._decode_nested_event(SNSMessage)
def _decode_nested_event(self, nested_event_class: Type[NestedEvent]) -> NestedEvent:
"""Returns the nested event source data object.
This is useful for handling events that are sent in the body of a SQS message.
Examples
--------
```python
data: S3Event = self._decode_nested_event(S3Event)
```
"""
return nested_event_class(self.json_body)
def record_handler(record: SQSRecord):
payload: str = record.body
if payload:
item: dict = json.loads(payload)
logger.info(item) | null |
5,460 | import json
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
batch_processor,
)
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.SQS)
def lambda_handler(event, context: LambdaContext):
return processor.response() | null |
5,461 | import httpx
from aws_lambda_powertools.utilities.batch import (
AsyncBatchProcessor,
EventType,
async_process_partial_response,
)
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = AsyncBatchProcessor(event_type=EventType.SQS)
async def async_record_handler(record: SQSRecord):
# Yield control back to the event loop to schedule other tasks
# while you await from a response from httpbin.org
async with httpx.AsyncClient() as client:
ret = await client.get("https://httpbin.org/get")
return ret.status_code
def lambda_handler(event, context: LambdaContext):
return async_process_partial_response(
event=event,
record_handler=async_record_handler,
processor=processor,
context=context,
) | null |
5,462 | import json
from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
process_partial_response,
)
from aws_lambda_powertools.utilities.data_classes.dynamo_db_stream_event import (
DynamoDBRecord,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.DynamoDBStreams)
def record_handler(record: DynamoDBRecord):
if record.dynamodb and record.dynamodb.new_image:
logger.info(record.dynamodb.new_image)
message = record.dynamodb.new_image.get("Message")
if message:
payload: dict = json.loads(message)
logger.info(payload)
def lambda_handler(event, context: LambdaContext):
return process_partial_response(event=event, record_handler=record_handler, processor=processor, context=context) | null |
5,463 | from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.utilities.batch import (
BatchProcessor,
EventType,
process_partial_response,
)
from aws_lambda_powertools.utilities.parser import BaseModel
from aws_lambda_powertools.utilities.parser.models import SqsRecordModel
from aws_lambda_powertools.utilities.parser.types import Json
from aws_lambda_powertools.utilities.typing import LambdaContext
processor = BatchProcessor(event_type=EventType.SQS, model=OrderSqsRecord)
def record_handler(record: OrderSqsRecord):
logger.info(record.body.item)
return record.body.item
def lambda_handler(event, context: LambdaContext):
return process_partial_response(event=event, record_handler=record_handler, processor=processor, context=context) | null |
5,464 | from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent_function,
)
from aws_lambda_powertools.utilities.parser import BaseModel
from aws_lambda_powertools.utilities.typing import LambdaContext
config = IdempotencyConfig(event_key_jmespath="order_id")
class OrderItem(BaseModel):
sku: str
description: str
class Order(BaseModel):
item: OrderItem
order_id: int
def process_order(order: Order):
return f"processed order {order.order_id}"
def lambda_handler(event: dict, context: LambdaContext):
config.register_lambda_context(context) # see Lambda timeouts section
order_item = OrderItem(sku="fake", description="sample")
order = Order(item=order_item, order_id=1)
# `order` parameter must be called as a keyword argument to work
process_order(order=order) | null |
5,465 | from dataclasses import dataclass
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent_function,
)
from aws_lambda_powertools.utilities.idempotency.serialization.dataclass import DataclassSerializer
from aws_lambda_powertools.utilities.typing import LambdaContext
config = IdempotencyConfig(event_key_jmespath="order_id")
class OrderItem:
class Order:
def process_order(order: Order):
def lambda_handler(event: dict, context: LambdaContext):
config.register_lambda_context(context) # see Lambda timeouts section
order_item = OrderItem(sku="fake", description="sample")
order = Order(item=order_item, order_id=1)
# `order` parameter must be called as a keyword argument to work
process_order(order=order) | null |
5,466 | from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
def lambda_handler(event, context: LambdaContext):
return event | null |
5,467 | from typing import Dict, Type
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent_function,
)
from aws_lambda_powertools.utilities.idempotency.serialization.custom_dict import CustomDictSerializer
from aws_lambda_powertools.utilities.typing import LambdaContext
class OrderOutput:
def __init__(self, order_id: int):
self.order_id = order_id
def order_to_dict(x: Type[OrderOutput]) -> Dict: # (1)!
return dict(x.__dict__) | null |
5,468 | from typing import Dict, Type
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent_function,
)
from aws_lambda_powertools.utilities.idempotency.serialization.custom_dict import CustomDictSerializer
from aws_lambda_powertools.utilities.typing import LambdaContext
class OrderOutput:
def __init__(self, order_id: int):
self.order_id = order_id
def dict_to_order(x: Dict) -> OrderOutput: # (2)!
return OrderOutput(**x) | null |
5,469 | from typing import Dict, Type
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent_function,
)
from aws_lambda_powertools.utilities.idempotency.serialization.custom_dict import CustomDictSerializer
from aws_lambda_powertools.utilities.typing import LambdaContext
config = IdempotencyConfig(event_key_jmespath="order_id")
class OrderItem:
def __init__(self, sku: str, description: str):
self.sku = sku
self.description = description
class Order:
def __init__(self, item: OrderItem, order_id: int):
self.item = item
self.order_id = order_id
config=config,
def process_order(order: Order) -> OrderOutput:
return OrderOutput(order_id=order.order_id)
def lambda_handler(event: dict, context: LambdaContext):
config.register_lambda_context(context) # see Lambda timeouts section
order_item = OrderItem(sku="fake", description="sample")
order = Order(item=order_item, order_id=1)
# `order` parameter must be called as a keyword argument to work
process_order(order=order) | null |
5,470 | from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent_function,
)
from aws_lambda_powertools.utilities.idempotency.serialization.pydantic import PydanticSerializer
from aws_lambda_powertools.utilities.parser import BaseModel
from aws_lambda_powertools.utilities.typing import LambdaContext
config = IdempotencyConfig(event_key_jmespath="order_id")
class OrderItem(BaseModel):
class Order(BaseModel):
def process_order(order: Order):
def lambda_handler(event: dict, context: LambdaContext):
config.register_lambda_context(context) # see Lambda timeouts section
order_item = OrderItem(sku="fake", description="sample")
order = Order(item=order_item, order_id=1)
# `order` parameter must be called as a keyword argument to work
process_order(order=order) | null |
5,471 | from dataclasses import dataclass, field
from uuid import uuid4
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
class Payment:
user_id: str
product_id: str
charge_type: str
amount: int
payment_id: str = field(default_factory=lambda: f"{uuid4()}")
class PaymentError(Exception):
...
def create_subscription_payment(event: dict) -> Payment:
return Payment(**event)
def lambda_handler(event: dict, context: LambdaContext):
try:
payment: Payment = create_subscription_payment(event)
return {
"payment_id": payment.payment_id,
"message": "success",
"statusCode": 200,
}
except Exception as exc:
raise PaymentError(f"Error creating payment {str(exc)}") | null |
5,472 | from dataclasses import dataclass, field
from uuid import uuid4
from redis import Redis
from aws_lambda_powertools.utilities.idempotency import (
idempotent,
)
from aws_lambda_powertools.utilities.idempotency.persistence.redis import (
RedisCachePersistenceLayer,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
class Payment:
user_id: str
product_id: str
payment_id: str = field(default_factory=lambda: f"{uuid4()}")
class PaymentError(Exception):
...
def create_subscription_payment(event: dict) -> Payment:
return Payment(**event)
def lambda_handler(event: dict, context: LambdaContext):
try:
payment: Payment = create_subscription_payment(event)
return {
"payment_id": payment.payment_id,
"message": "success",
"statusCode": 200,
}
except Exception as exc:
raise PaymentError(f"Error creating payment {str(exc)}") | null |
5,473 | from aws_lambda_powertools import Logger
from aws_lambda_powertools.utilities.batch import BatchProcessor, EventType
from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent_function,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger()
processor = BatchProcessor(event_type=EventType.SQS)
config = IdempotencyConfig(
event_key_jmespath="messageId", # see Choosing a payload subset section
)
def record_handler(record: SQSRecord):
return {"message": record.body}
class SQSRecord(DictWrapper):
"""An Amazon SQS message"""
NestedEvent = TypeVar("NestedEvent", bound=DictWrapper)
def message_id(self) -> str:
"""A unique identifier for the message.
A messageId is considered unique across all AWS accounts for an extended period of time."""
return self["messageId"]
def receipt_handle(self) -> str:
"""An identifier associated with the act of receiving the message.
A new receipt handle is returned every time you receive a message. When deleting a message,
you provide the last received receipt handle to delete the message."""
return self["receiptHandle"]
def body(self) -> str:
"""The message's contents (not URL-encoded)."""
return self["body"]
def json_body(self) -> Any:
"""Deserializes JSON string available in 'body' property
Notes
-----
**Strict typing**
Caller controls the type as we can't use recursive generics here.
JSON Union types would force caller to have to cast a type. Instead,
we choose Any to ease ergonomics and other tools receiving this data.
Examples
--------
**Type deserialized data from JSON string**
```python
data: dict = record.json_body # {"telemetry": [], ...}
# or
data: list = record.json_body # ["telemetry_values"]
```
"""
return self._json_deserializer(self["body"])
def attributes(self) -> SQSRecordAttributes:
"""A map of the attributes requested in ReceiveMessage to their respective values."""
return SQSRecordAttributes(self["attributes"])
def message_attributes(self) -> SQSMessageAttributes:
"""Each message attribute consists of a Name, Type, and Value."""
return SQSMessageAttributes(self["messageAttributes"])
def md5_of_body(self) -> str:
"""An MD5 digest of the non-URL-encoded message body string."""
return self["md5OfBody"]
def event_source(self) -> str:
"""The AWS service from which the SQS record originated. For SQS, this is `aws:sqs`"""
return self["eventSource"]
def event_source_arn(self) -> str:
"""The Amazon Resource Name (ARN) of the event source"""
return self["eventSourceARN"]
def aws_region(self) -> str:
"""aws region eg: us-east-1"""
return self["awsRegion"]
def queue_url(self) -> str:
"""The URL of the queue."""
arn_parts = self["eventSourceARN"].split(":")
region = arn_parts[3]
account_id = arn_parts[4]
queue_name = arn_parts[5]
queue_url = f"https://sqs.{region}.amazonaws.com/{account_id}/{queue_name}"
return queue_url
def decoded_nested_s3_event(self) -> S3Event:
"""Returns the nested `S3Event` object that is sent in the body of a SQS message.
Even though you can typecast the object returned by `record.json_body`
directly, this method is provided as a shortcut for convenience.
Notes
-----
This method does not validate whether the SQS message body is actually a valid S3 event.
Examples
--------
```python
nested_event: S3Event = record.decoded_nested_s3_event
```
"""
return self._decode_nested_event(S3Event)
def decoded_nested_sns_event(self) -> SNSMessage:
"""Returns the nested `SNSMessage` object that is sent in the body of a SQS message.
Even though you can typecast the object returned by `record.json_body`
directly, this method is provided as a shortcut for convenience.
Notes
-----
This method does not validate whether the SQS message body is actually
a valid SNS message.
Examples
--------
```python
nested_message: SNSMessage = record.decoded_nested_sns_event
```
"""
return self._decode_nested_event(SNSMessage)
def _decode_nested_event(self, nested_event_class: Type[NestedEvent]) -> NestedEvent:
"""Returns the nested event source data object.
This is useful for handling events that are sent in the body of a SQS message.
Examples
--------
```python
data: S3Event = self._decode_nested_event(S3Event)
```
"""
return nested_event_class(self.json_body)
def lambda_handler(event: SQSRecord, context: LambdaContext):
config.register_lambda_context(context) # see Lambda timeouts section
# with Lambda context registered for Idempotency
# we can now kick in the Bach processing logic
batch = event["Records"]
with processor(records=batch, handler=record_handler):
# in case you want to access each record processed by your record_handler
# otherwise ignore the result variable assignment
processed_messages = processor.process()
logger.info(processed_messages)
return processor.response() | null |
5,474 | from dataclasses import dataclass
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent_function,
)
from aws_lambda_powertools.utilities.idempotency.serialization.dataclass import DataclassSerializer
from aws_lambda_powertools.utilities.typing import LambdaContext
config = IdempotencyConfig(event_key_jmespath="order_id")
class OrderItem:
sku: str
description: str
class Order:
item: OrderItem
order_id: int
def process_order(order: Order) -> OrderOutput: # (1)!
return OrderOutput(order_id=order.order_id)
def lambda_handler(event: dict, context: LambdaContext):
config.register_lambda_context(context) # see Lambda timeouts section
order_item = OrderItem(sku="fake", description="sample")
order = Order(item=order_item, order_id=1)
# `order` parameter must be called as a keyword argument to work
process_order(order=order) | null |
5,475 | from typing import Any
from redis import Redis
from aws_lambda_powertools.shared.functions import abs_lambda_path
from aws_lambda_powertools.utilities import parameters
from aws_lambda_powertools.utilities.idempotency import IdempotencyConfig, idempotent
from aws_lambda_powertools.utilities.idempotency.persistence.redis import (
RedisCachePersistenceLayer,
)
def lambda_handler(event, context):
return {"message": "Hello"} | null |
5,476 | from botocore.config import Config
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return event | null |
5,477 | from typing import Any
from redis import Redis
from aws_lambda_powertools.utilities import parameters
from aws_lambda_powertools.utilities.idempotency import IdempotencyConfig, idempotent
from aws_lambda_powertools.utilities.idempotency.persistence.redis import (
RedisCachePersistenceLayer,
)
def lambda_handler(event, context):
return {"message": "Hello"} | null |
5,478 | from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent_function,
)
from aws_lambda_powertools.utilities.idempotency.serialization.pydantic import PydanticSerializer
from aws_lambda_powertools.utilities.parser import BaseModel
from aws_lambda_powertools.utilities.typing import LambdaContext
config = IdempotencyConfig(event_key_jmespath="order_id")
class OrderItem(BaseModel):
sku: str
description: str
class Order(BaseModel):
item: OrderItem
order_id: int
def process_order(order: Order) -> OrderOutput: # (1)!
return OrderOutput(order_id=order.order_id)
def lambda_handler(event: dict, context: LambdaContext):
config.register_lambda_context(context) # see Lambda timeouts section
order_item = OrderItem(sku="fake", description="sample")
order = Order(item=order_item, order_id=1)
# `order` parameter must be called as a keyword argument to work
process_order(order=order) | null |
5,479 | import boto3
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return event | null |
5,480 | from aws_lambda_powertools.utilities.idempotency import (
idempotent,
)
from aws_lambda_powertools.utilities.idempotency.persistence.redis import (
RedisCachePersistenceLayer,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return event | null |
5,482 | from dataclasses import dataclass, field
from uuid import uuid4
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
idempotent,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
class Payment:
user_id: str
product_id: str
payment_id: str = field(default_factory=lambda: f"{uuid4()}")
class PaymentError(Exception):
...
def create_subscription_payment(event: dict) -> Payment:
return Payment(**event)
def lambda_handler(event: dict, context: LambdaContext):
try:
payment: Payment = create_subscription_payment(event)
return {
"payment_id": payment.payment_id,
"message": "success",
"statusCode": 200,
}
except Exception as exc:
raise PaymentError(f"Error creating payment {str(exc)}") | null |
5,483 | from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
from aws_lambda_powertools.utilities.validation import envelopes, validator
def lambda_handler(event, context: LambdaContext):
return {"message": event["message"], "statusCode": 200} | null |
5,484 | from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
idempotent,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return event | null |
5,485 | from dataclasses import dataclass, field
from uuid import uuid4
from aws_lambda_powertools.utilities.idempotency import (
idempotent,
)
from aws_lambda_powertools.utilities.idempotency.persistence.redis import (
RedisCachePersistenceLayer,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
class Payment:
class PaymentError(Exception):
def create_subscription_payment(event: dict) -> Payment:
def lambda_handler(event: dict, context: LambdaContext):
try:
payment: Payment = create_subscription_payment(event)
return {
"payment_id": payment.payment_id,
"message": "success",
"statusCode": 200,
}
except Exception as exc:
raise PaymentError(f"Error creating payment {str(exc)}") | null |
5,486 | from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
idempotent,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
def lambda_handler(event: dict, context: LambdaContext) -> dict:
user_id: str = event.get("body", "")["user_id"]
return {"message": "success", "user_id": user_id} | null |
5,487 | import requests
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent_function,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
def call_external_service(data: dict):
result: requests.Response = requests.post(
"https://jsonplaceholder.typicode.com/comments/",
json={"user": data["user"], "transaction_id": data["id"]},
)
return result.json()
def lambda_handler(event: dict, context: LambdaContext):
# If an exception is raised here, no idempotent record will ever get created as the
# idempotent function does not get called
try:
endpoint = "https://jsonplaceholder.typicode.com/comments/" # change this endpoint to force an exception
requests.get(endpoint)
except Exception as exc:
return str(exc)
call_external_service(data={"user": "user1", "id": 5})
# This exception will not cause the idempotent record to be deleted, since it
# happens after the decorated function has been successfully called
raise Exception | null |
5,488 | from dataclasses import dataclass
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent_function,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
config = IdempotencyConfig(event_key_jmespath="order_id")
class OrderItem:
sku: str
description: str
class Order:
item: OrderItem
order_id: int
def process_order(order: Order):
return f"processed order {order.order_id}"
def lambda_handler(event: dict, context: LambdaContext):
config.register_lambda_context(context) # see Lambda timeouts section
order_item = OrderItem(sku="fake", description="sample")
order = Order(item=order_item, order_id=1)
# `order` parameter must be called as a keyword argument to work
process_order(order=order) | null |
5,489 | import json
from dataclasses import dataclass, field
from uuid import uuid4
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
class Payment:
class PaymentError(Exception):
def create_subscription_payment(event: dict) -> Payment:
def lambda_handler(event: dict, context: LambdaContext):
try:
payment_info: str = event.get("body", "")
payment: Payment = create_subscription_payment(json.loads(payment_info))
return {
"payment_id": payment.payment_id,
"message": "success",
"statusCode": 200,
}
except Exception as exc:
raise PaymentError(f"Error creating payment {str(exc)}") | null |
5,490 | from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
def lambda_handler(event: dict, context: LambdaContext) -> dict:
return event | null |
5,491 | from aws_lambda_powertools.utilities.data_classes.sqs_event import SQSRecord
from aws_lambda_powertools.utilities.idempotency import (
DynamoDBPersistenceLayer,
IdempotencyConfig,
idempotent_function,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
config = IdempotencyConfig()
def record_handler(record: SQSRecord):
return {"message": record["body"]}
def lambda_handler(event: dict, context: LambdaContext):
config.register_lambda_context(context)
return record_handler(event) | null |
5,492 | import io
import boto3
from assert_transformation_module import UpperTransform
from botocore import stub
from aws_lambda_powertools.utilities.streaming import S3Object
from aws_lambda_powertools.utilities.streaming.compat import PowertoolsStreamingBody
class UpperTransform(BaseTransform):
def transform(self, input_stream: IO[bytes]) -> UpperIO:
return UpperIO(input_stream=input_stream, encoding="utf-8")
def test_upper_transform():
# GIVEN
data_stream = io.BytesIO(b"hello world")
# WHEN
data_stream = UpperTransform().transform(data_stream)
# THEN
assert data_stream.read() == b"HELLO WORLD" | null |
5,493 | import io
import boto3
from assert_transformation_module import UpperTransform
from botocore import stub
from aws_lambda_powertools.utilities.streaming import S3Object
from aws_lambda_powertools.utilities.streaming.compat import PowertoolsStreamingBody
class UpperTransform(BaseTransform):
def transform(self, input_stream: IO[bytes]) -> UpperIO:
PowertoolsStreamingBody = StreamingBody
def test_s3_object_with_upper_transform():
# GIVEN
payload = b"hello world"
s3_client = boto3.client("s3")
s3_stub = stub.Stubber(s3_client)
s3_stub.add_response(
"get_object",
{"Body": PowertoolsStreamingBody(raw_stream=io.BytesIO(payload), content_length=len(payload))},
)
s3_stub.activate()
# WHEN
data_stream = S3Object(bucket="bucket", key="key", boto3_client=s3_client)
data_stream.transform(UpperTransform(), in_place=True)
# THEN
assert data_stream.read() == b"HELLO WORLD" | null |
5,494 | from typing import Dict
from aws_lambda_powertools.utilities.streaming.s3_object import S3Object
from aws_lambda_powertools.utilities.streaming.transformations import (
CsvTransform,
GzipTransform,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
class S3Object(IO[bytes]):
"""
Seekable and streamable S3 Object reader.
S3Object implements the IO[bytes], backed by a seekable S3 streaming.
Parameters
----------
bucket: str
The S3 bucket
key: str
The S3 key
version_id: str, optional
A version ID of the object, when the S3 bucket is versioned
boto3_client: S3Client, optional
An optional boto3 S3 client. If missing, a new one will be created.
is_gzip: bool, optional
Enables the Gunzip data transformation
is_csv: bool, optional
Enables the CSV data transformation
sdk_options: dict, optional
Dictionary of options that will be passed to the S3 Client get_object API call
Example
-------
**Reads a line from an S3, loading as little data as necessary:**
>>> from aws_lambda_powertools.utilities.streaming import S3Object
>>>
>>> line: bytes = S3Object(bucket="bucket", key="key").readline()
>>>
>>> print(line)
"""
def __init__(
self,
bucket: str,
key: str,
version_id: Optional[str] = None,
boto3_client: Optional["Client"] = None,
is_gzip: Optional[bool] = False,
is_csv: Optional[bool] = False,
**sdk_options,
):
self.bucket = bucket
self.key = key
self.version_id = version_id
# The underlying seekable IO, where all the magic happens
self.raw_stream = _S3SeekableIO(
bucket=bucket,
key=key,
version_id=version_id,
boto3_client=boto3_client,
**sdk_options,
)
# Stores the list of data transformations
self._data_transformations: List[BaseTransform] = []
if is_gzip:
self._data_transformations.append(GzipTransform())
if is_csv:
self._data_transformations.append(CsvTransform())
# Stores the cached transformed stream
self._transformed_stream: Optional[IO[bytes]] = None
def size(self) -> int:
"""
Retrieves the size of the underlying S3 object
"""
return self.raw_stream.size
def transformed_stream(self) -> IO[bytes]:
"""
Returns a IO[bytes] stream with all the data transformations applied in order
"""
if self._transformed_stream is None:
# Create a stream which is the result of applying all the data transformations
# To start with, our transformed stream is the same as our raw seekable stream.
# This means that if there are no data transformations to be applied, IO is just
# delegated directly to the raw_stream.
transformed_stream = self.raw_stream
# Now we apply each transformation in order
# e.g: when self._data_transformations is [transform_1, transform_2], then
# transformed_stream is the equivalent of doing transform_2(transform_1(...(raw_stream)))
for transformation in self._data_transformations:
transformed_stream = transformation.transform(transformed_stream)
self._transformed_stream = transformed_stream
return self._transformed_stream
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]], in_place: Literal[True]) -> T:
pass
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Literal[False],
) -> None:
pass
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]]) -> T:
pass
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Optional[bool] = False,
) -> Optional[T]:
"""
Applies one or more data transformations to the stream.
Parameters
----------
transformations: BaseTransform[T] | Sequence[BaseTransform[T]]
One or more transformations to apply. Transformations are applied in the same order as they are declared.
in_place: bool, optional
Transforms the stream in place, instead of returning a new stream object. Defaults to false.
Returns
-------
T[bound=IO[bytes]], optional
If in_place is False, returns an IO[bytes] object representing the transformed stream
"""
# Make transformations always be a sequence to make mypy happy
if not isinstance(transformations, Sequence):
transformations = [transformations]
# Scenario 1: user wants to transform the stream in place.
# In this case, we store the transformations and invalidate any existing transformed stream.
# This way, the transformed_stream is re-created on the next IO operation.
# This can happen when the user calls .transform multiple times before they start reading data
#
# >>> s3object.transform(GzipTransform(), in_place=True)
# >>> s3object.seek(0, io.SEEK_SET) <- this creates a transformed stream
# >>> s3object.transform(CsvTransform(), in_place=True) <- need to re-create transformed stream
# >>> s3object.read...
if in_place:
self._data_transformations.extend(transformations)
# Invalidate any existing transformed stream.
# It will be created again next time it's accessed.
self._transformed_stream = None
return None
else:
# Tell mypy that raw_stream actually implements T (bound to IO[bytes])
stream = cast(T, self.raw_stream)
for transformation in transformations:
stream = transformation.transform(stream)
return stream
# From this point on, we're just implementing all the standard methods on the IO[bytes] type.
# There's no magic here, just delegating all the calls to our transformed_stream.
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
return self.transformed_stream.seek(offset, whence)
def seekable(self) -> bool:
return self.transformed_stream.seekable()
def readable(self) -> bool:
return self.transformed_stream.readable()
def writable(self) -> bool:
return self.transformed_stream.writable()
def tell(self) -> int:
return self.transformed_stream.tell()
def closed(self) -> bool:
return self.transformed_stream.closed
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def close(self):
# Scenario 1: S3Object = SeekableIO, because there are no data transformations applied
# In this scenario, we can only close the raw_stream. If we tried to also close the transformed_stream we would
# get an error, since they are the same object, and we can't close the same stream twice.
self.raw_stream.close()
# Scenario 2: S3Object -> [Transformations] -> SeekableIO, because there are data transformations applied
# In this scenario, we also need to close the transformed_stream if it exists. The reason we test for
# existence is that the user might want to close the object without reading data from it. Example:
#
# >>> s3object = S3Object(...., is_gzip=True)
# >>> s3object.close() <- transformed_stream doesn't exist yet at this point
if self.raw_stream != self._transformed_stream and self._transformed_stream is not None:
self._transformed_stream.close()
def read(self, size: int = -1) -> bytes:
return self.transformed_stream.read(size)
def readline(self, size: Optional[int] = -1) -> bytes:
return self.transformed_stream.readline()
def readlines(self, hint: int = -1) -> List[bytes]:
return self.transformed_stream.readlines(hint)
def __next__(self):
return self.transformed_stream.__next__()
def __iter__(self):
return self.transformed_stream.__iter__()
def fileno(self) -> int:
raise NotImplementedError("this stream is not backed by a file descriptor")
def flush(self) -> None:
raise NotImplementedError("this stream is not writable")
def isatty(self) -> bool:
return False
def truncate(self, size: Optional[int] = 0) -> int:
raise NotImplementedError("this stream is not writable")
def write(self, data: Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]) -> int:
raise NotImplementedError("this stream is not writable")
def writelines(
self,
data: Iterable[Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]],
) -> None:
raise NotImplementedError("this stream is not writable")
def lambda_handler(event: Dict[str, str], context: LambdaContext):
s3 = S3Object(bucket=event["bucket"], key=event["key"])
data = s3.transform([GzipTransform(), CsvTransform()])
for line in data:
print(line) # returns a dict | null |
5,495 | from typing import Dict
from aws_lambda_powertools.utilities.streaming.s3_object import S3Object
from aws_lambda_powertools.utilities.typing import LambdaContext
class S3Object(IO[bytes]):
"""
Seekable and streamable S3 Object reader.
S3Object implements the IO[bytes], backed by a seekable S3 streaming.
Parameters
----------
bucket: str
The S3 bucket
key: str
The S3 key
version_id: str, optional
A version ID of the object, when the S3 bucket is versioned
boto3_client: S3Client, optional
An optional boto3 S3 client. If missing, a new one will be created.
is_gzip: bool, optional
Enables the Gunzip data transformation
is_csv: bool, optional
Enables the CSV data transformation
sdk_options: dict, optional
Dictionary of options that will be passed to the S3 Client get_object API call
Example
-------
**Reads a line from an S3, loading as little data as necessary:**
>>> from aws_lambda_powertools.utilities.streaming import S3Object
>>>
>>> line: bytes = S3Object(bucket="bucket", key="key").readline()
>>>
>>> print(line)
"""
def __init__(
self,
bucket: str,
key: str,
version_id: Optional[str] = None,
boto3_client: Optional["Client"] = None,
is_gzip: Optional[bool] = False,
is_csv: Optional[bool] = False,
**sdk_options,
):
self.bucket = bucket
self.key = key
self.version_id = version_id
# The underlying seekable IO, where all the magic happens
self.raw_stream = _S3SeekableIO(
bucket=bucket,
key=key,
version_id=version_id,
boto3_client=boto3_client,
**sdk_options,
)
# Stores the list of data transformations
self._data_transformations: List[BaseTransform] = []
if is_gzip:
self._data_transformations.append(GzipTransform())
if is_csv:
self._data_transformations.append(CsvTransform())
# Stores the cached transformed stream
self._transformed_stream: Optional[IO[bytes]] = None
def size(self) -> int:
"""
Retrieves the size of the underlying S3 object
"""
return self.raw_stream.size
def transformed_stream(self) -> IO[bytes]:
"""
Returns a IO[bytes] stream with all the data transformations applied in order
"""
if self._transformed_stream is None:
# Create a stream which is the result of applying all the data transformations
# To start with, our transformed stream is the same as our raw seekable stream.
# This means that if there are no data transformations to be applied, IO is just
# delegated directly to the raw_stream.
transformed_stream = self.raw_stream
# Now we apply each transformation in order
# e.g: when self._data_transformations is [transform_1, transform_2], then
# transformed_stream is the equivalent of doing transform_2(transform_1(...(raw_stream)))
for transformation in self._data_transformations:
transformed_stream = transformation.transform(transformed_stream)
self._transformed_stream = transformed_stream
return self._transformed_stream
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]], in_place: Literal[True]) -> T:
pass
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Literal[False],
) -> None:
pass
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]]) -> T:
pass
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Optional[bool] = False,
) -> Optional[T]:
"""
Applies one or more data transformations to the stream.
Parameters
----------
transformations: BaseTransform[T] | Sequence[BaseTransform[T]]
One or more transformations to apply. Transformations are applied in the same order as they are declared.
in_place: bool, optional
Transforms the stream in place, instead of returning a new stream object. Defaults to false.
Returns
-------
T[bound=IO[bytes]], optional
If in_place is False, returns an IO[bytes] object representing the transformed stream
"""
# Make transformations always be a sequence to make mypy happy
if not isinstance(transformations, Sequence):
transformations = [transformations]
# Scenario 1: user wants to transform the stream in place.
# In this case, we store the transformations and invalidate any existing transformed stream.
# This way, the transformed_stream is re-created on the next IO operation.
# This can happen when the user calls .transform multiple times before they start reading data
#
# >>> s3object.transform(GzipTransform(), in_place=True)
# >>> s3object.seek(0, io.SEEK_SET) <- this creates a transformed stream
# >>> s3object.transform(CsvTransform(), in_place=True) <- need to re-create transformed stream
# >>> s3object.read...
if in_place:
self._data_transformations.extend(transformations)
# Invalidate any existing transformed stream.
# It will be created again next time it's accessed.
self._transformed_stream = None
return None
else:
# Tell mypy that raw_stream actually implements T (bound to IO[bytes])
stream = cast(T, self.raw_stream)
for transformation in transformations:
stream = transformation.transform(stream)
return stream
# From this point on, we're just implementing all the standard methods on the IO[bytes] type.
# There's no magic here, just delegating all the calls to our transformed_stream.
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
return self.transformed_stream.seek(offset, whence)
def seekable(self) -> bool:
return self.transformed_stream.seekable()
def readable(self) -> bool:
return self.transformed_stream.readable()
def writable(self) -> bool:
return self.transformed_stream.writable()
def tell(self) -> int:
return self.transformed_stream.tell()
def closed(self) -> bool:
return self.transformed_stream.closed
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def close(self):
# Scenario 1: S3Object = SeekableIO, because there are no data transformations applied
# In this scenario, we can only close the raw_stream. If we tried to also close the transformed_stream we would
# get an error, since they are the same object, and we can't close the same stream twice.
self.raw_stream.close()
# Scenario 2: S3Object -> [Transformations] -> SeekableIO, because there are data transformations applied
# In this scenario, we also need to close the transformed_stream if it exists. The reason we test for
# existence is that the user might want to close the object without reading data from it. Example:
#
# >>> s3object = S3Object(...., is_gzip=True)
# >>> s3object.close() <- transformed_stream doesn't exist yet at this point
if self.raw_stream != self._transformed_stream and self._transformed_stream is not None:
self._transformed_stream.close()
def read(self, size: int = -1) -> bytes:
return self.transformed_stream.read(size)
def readline(self, size: Optional[int] = -1) -> bytes:
return self.transformed_stream.readline()
def readlines(self, hint: int = -1) -> List[bytes]:
return self.transformed_stream.readlines(hint)
def __next__(self):
return self.transformed_stream.__next__()
def __iter__(self):
return self.transformed_stream.__iter__()
def fileno(self) -> int:
raise NotImplementedError("this stream is not backed by a file descriptor")
def flush(self) -> None:
raise NotImplementedError("this stream is not writable")
def isatty(self) -> bool:
return False
def truncate(self, size: Optional[int] = 0) -> int:
raise NotImplementedError("this stream is not writable")
def write(self, data: Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]) -> int:
raise NotImplementedError("this stream is not writable")
def writelines(
self,
data: Iterable[Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]],
) -> None:
raise NotImplementedError("this stream is not writable")
def lambda_handler(event: Dict[str, str], context: LambdaContext):
s3 = S3Object(bucket=event["bucket"], key=event["key"])
for line in s3:
print(line) | null |
5,496 | import io
from typing import Dict
from aws_lambda_powertools.utilities.streaming.s3_object import S3Object
from aws_lambda_powertools.utilities.streaming.transformations import CsvTransform
from aws_lambda_powertools.utilities.typing import LambdaContext
LAST_ROW_SIZE = 30
CSV_HEADERS = ["id", "name", "location"]
class S3Object(IO[bytes]):
def __init__(
self,
bucket: str,
key: str,
version_id: Optional[str] = None,
boto3_client: Optional["Client"] = None,
is_gzip: Optional[bool] = False,
is_csv: Optional[bool] = False,
**sdk_options,
):
def size(self) -> int:
def transformed_stream(self) -> IO[bytes]:
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]], in_place: Literal[True]) -> T:
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Literal[False],
) -> None:
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]]) -> T:
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Optional[bool] = False,
) -> Optional[T]:
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
def seekable(self) -> bool:
def readable(self) -> bool:
def writable(self) -> bool:
def tell(self) -> int:
def closed(self) -> bool:
def __enter__(self):
def __exit__(self, *args):
def close(self):
def read(self, size: int = -1) -> bytes:
def readline(self, size: Optional[int] = -1) -> bytes:
def readlines(self, hint: int = -1) -> List[bytes]:
def __next__(self):
def __iter__(self):
def fileno(self) -> int:
def flush(self) -> None:
def isatty(self) -> bool:
def truncate(self, size: Optional[int] = 0) -> int:
def write(self, data: Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]) -> int:
def writelines(
self,
data: Iterable[Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]],
) -> None:
def lambda_handler(event: Dict[str, str], context: LambdaContext):
sample_csv = S3Object(bucket=event["bucket"], key="sample.csv")
# From the end of the file, jump exactly 30 bytes backwards
sample_csv.seek(-LAST_ROW_SIZE, io.SEEK_END)
# Transform portion of data into CSV with our headers
sample_csv.transform(CsvTransform(fieldnames=CSV_HEADERS), in_place=True)
# We will only read the last portion of the file from S3
# as we're only interested in the last 'location' from our dataset
for last_row in sample_csv:
print(last_row["location"]) | null |
5,497 | from typing import Dict
from aws_lambda_powertools.utilities.streaming.s3_object import S3Object
from aws_lambda_powertools.utilities.typing import LambdaContext
class S3Object(IO[bytes]):
def __init__(
self,
bucket: str,
key: str,
version_id: Optional[str] = None,
boto3_client: Optional["Client"] = None,
is_gzip: Optional[bool] = False,
is_csv: Optional[bool] = False,
**sdk_options,
):
def size(self) -> int:
def transformed_stream(self) -> IO[bytes]:
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]], in_place: Literal[True]) -> T:
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Literal[False],
) -> None:
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]]) -> T:
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Optional[bool] = False,
) -> Optional[T]:
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
def seekable(self) -> bool:
def readable(self) -> bool:
def writable(self) -> bool:
def tell(self) -> int:
def closed(self) -> bool:
def __enter__(self):
def __exit__(self, *args):
def close(self):
def read(self, size: int = -1) -> bytes:
def readline(self, size: Optional[int] = -1) -> bytes:
def readlines(self, hint: int = -1) -> List[bytes]:
def __next__(self):
def __iter__(self):
def fileno(self) -> int:
def flush(self) -> None:
def isatty(self) -> bool:
def truncate(self, size: Optional[int] = 0) -> int:
def write(self, data: Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]) -> int:
def writelines(
self,
data: Iterable[Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]],
) -> None:
def lambda_handler(event: Dict[str, str], context: LambdaContext):
s3 = S3Object(bucket=event["bucket"], key=event["key"], is_gzip=True, is_csv=True)
for line in s3:
print(line) | null |
5,498 | import zipfile
from typing import Dict
from aws_lambda_powertools.utilities.streaming.s3_object import S3Object
from aws_lambda_powertools.utilities.streaming.transformations import ZipTransform
from aws_lambda_powertools.utilities.typing import LambdaContext
class S3Object(IO[bytes]):
"""
Seekable and streamable S3 Object reader.
S3Object implements the IO[bytes], backed by a seekable S3 streaming.
Parameters
----------
bucket: str
The S3 bucket
key: str
The S3 key
version_id: str, optional
A version ID of the object, when the S3 bucket is versioned
boto3_client: S3Client, optional
An optional boto3 S3 client. If missing, a new one will be created.
is_gzip: bool, optional
Enables the Gunzip data transformation
is_csv: bool, optional
Enables the CSV data transformation
sdk_options: dict, optional
Dictionary of options that will be passed to the S3 Client get_object API call
Example
-------
**Reads a line from an S3, loading as little data as necessary:**
>>> from aws_lambda_powertools.utilities.streaming import S3Object
>>>
>>> line: bytes = S3Object(bucket="bucket", key="key").readline()
>>>
>>> print(line)
"""
def __init__(
self,
bucket: str,
key: str,
version_id: Optional[str] = None,
boto3_client: Optional["Client"] = None,
is_gzip: Optional[bool] = False,
is_csv: Optional[bool] = False,
**sdk_options,
):
self.bucket = bucket
self.key = key
self.version_id = version_id
# The underlying seekable IO, where all the magic happens
self.raw_stream = _S3SeekableIO(
bucket=bucket,
key=key,
version_id=version_id,
boto3_client=boto3_client,
**sdk_options,
)
# Stores the list of data transformations
self._data_transformations: List[BaseTransform] = []
if is_gzip:
self._data_transformations.append(GzipTransform())
if is_csv:
self._data_transformations.append(CsvTransform())
# Stores the cached transformed stream
self._transformed_stream: Optional[IO[bytes]] = None
def size(self) -> int:
"""
Retrieves the size of the underlying S3 object
"""
return self.raw_stream.size
def transformed_stream(self) -> IO[bytes]:
"""
Returns a IO[bytes] stream with all the data transformations applied in order
"""
if self._transformed_stream is None:
# Create a stream which is the result of applying all the data transformations
# To start with, our transformed stream is the same as our raw seekable stream.
# This means that if there are no data transformations to be applied, IO is just
# delegated directly to the raw_stream.
transformed_stream = self.raw_stream
# Now we apply each transformation in order
# e.g: when self._data_transformations is [transform_1, transform_2], then
# transformed_stream is the equivalent of doing transform_2(transform_1(...(raw_stream)))
for transformation in self._data_transformations:
transformed_stream = transformation.transform(transformed_stream)
self._transformed_stream = transformed_stream
return self._transformed_stream
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]], in_place: Literal[True]) -> T:
pass
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Literal[False],
) -> None:
pass
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]]) -> T:
pass
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Optional[bool] = False,
) -> Optional[T]:
"""
Applies one or more data transformations to the stream.
Parameters
----------
transformations: BaseTransform[T] | Sequence[BaseTransform[T]]
One or more transformations to apply. Transformations are applied in the same order as they are declared.
in_place: bool, optional
Transforms the stream in place, instead of returning a new stream object. Defaults to false.
Returns
-------
T[bound=IO[bytes]], optional
If in_place is False, returns an IO[bytes] object representing the transformed stream
"""
# Make transformations always be a sequence to make mypy happy
if not isinstance(transformations, Sequence):
transformations = [transformations]
# Scenario 1: user wants to transform the stream in place.
# In this case, we store the transformations and invalidate any existing transformed stream.
# This way, the transformed_stream is re-created on the next IO operation.
# This can happen when the user calls .transform multiple times before they start reading data
#
# >>> s3object.transform(GzipTransform(), in_place=True)
# >>> s3object.seek(0, io.SEEK_SET) <- this creates a transformed stream
# >>> s3object.transform(CsvTransform(), in_place=True) <- need to re-create transformed stream
# >>> s3object.read...
if in_place:
self._data_transformations.extend(transformations)
# Invalidate any existing transformed stream.
# It will be created again next time it's accessed.
self._transformed_stream = None
return None
else:
# Tell mypy that raw_stream actually implements T (bound to IO[bytes])
stream = cast(T, self.raw_stream)
for transformation in transformations:
stream = transformation.transform(stream)
return stream
# From this point on, we're just implementing all the standard methods on the IO[bytes] type.
# There's no magic here, just delegating all the calls to our transformed_stream.
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
return self.transformed_stream.seek(offset, whence)
def seekable(self) -> bool:
return self.transformed_stream.seekable()
def readable(self) -> bool:
return self.transformed_stream.readable()
def writable(self) -> bool:
return self.transformed_stream.writable()
def tell(self) -> int:
return self.transformed_stream.tell()
def closed(self) -> bool:
return self.transformed_stream.closed
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def close(self):
# Scenario 1: S3Object = SeekableIO, because there are no data transformations applied
# In this scenario, we can only close the raw_stream. If we tried to also close the transformed_stream we would
# get an error, since they are the same object, and we can't close the same stream twice.
self.raw_stream.close()
# Scenario 2: S3Object -> [Transformations] -> SeekableIO, because there are data transformations applied
# In this scenario, we also need to close the transformed_stream if it exists. The reason we test for
# existence is that the user might want to close the object without reading data from it. Example:
#
# >>> s3object = S3Object(...., is_gzip=True)
# >>> s3object.close() <- transformed_stream doesn't exist yet at this point
if self.raw_stream != self._transformed_stream and self._transformed_stream is not None:
self._transformed_stream.close()
def read(self, size: int = -1) -> bytes:
return self.transformed_stream.read(size)
def readline(self, size: Optional[int] = -1) -> bytes:
return self.transformed_stream.readline()
def readlines(self, hint: int = -1) -> List[bytes]:
return self.transformed_stream.readlines(hint)
def __next__(self):
return self.transformed_stream.__next__()
def __iter__(self):
return self.transformed_stream.__iter__()
def fileno(self) -> int:
raise NotImplementedError("this stream is not backed by a file descriptor")
def flush(self) -> None:
raise NotImplementedError("this stream is not writable")
def isatty(self) -> bool:
return False
def truncate(self, size: Optional[int] = 0) -> int:
raise NotImplementedError("this stream is not writable")
def write(self, data: Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]) -> int:
raise NotImplementedError("this stream is not writable")
def writelines(
self,
data: Iterable[Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]],
) -> None:
raise NotImplementedError("this stream is not writable")
def lambda_handler(event: Dict[str, str], context: LambdaContext):
s3 = S3Object(bucket=event["bucket"], key=event["key"])
zf = s3.transform(ZipTransform(compression=zipfile.ZIP_LZMA))
print(zf.nameslist())
zf.extract(zf.namelist()[0], "/tmp") | null |
5,499 | import io
from typing import Dict
from aws_lambda_powertools.utilities.streaming.s3_object import S3Object
from aws_lambda_powertools.utilities.streaming.transformations import CsvTransform
from aws_lambda_powertools.utilities.typing import LambdaContext
ROW_SIZE = 8 + 1
HEADER_SIZE = 21 + 1
LINES_TO_JUMP = 100
class S3Object(IO[bytes]):
"""
Seekable and streamable S3 Object reader.
S3Object implements the IO[bytes], backed by a seekable S3 streaming.
Parameters
----------
bucket: str
The S3 bucket
key: str
The S3 key
version_id: str, optional
A version ID of the object, when the S3 bucket is versioned
boto3_client: S3Client, optional
An optional boto3 S3 client. If missing, a new one will be created.
is_gzip: bool, optional
Enables the Gunzip data transformation
is_csv: bool, optional
Enables the CSV data transformation
sdk_options: dict, optional
Dictionary of options that will be passed to the S3 Client get_object API call
Example
-------
**Reads a line from an S3, loading as little data as necessary:**
>>> from aws_lambda_powertools.utilities.streaming import S3Object
>>>
>>> line: bytes = S3Object(bucket="bucket", key="key").readline()
>>>
>>> print(line)
"""
def __init__(
self,
bucket: str,
key: str,
version_id: Optional[str] = None,
boto3_client: Optional["Client"] = None,
is_gzip: Optional[bool] = False,
is_csv: Optional[bool] = False,
**sdk_options,
):
self.bucket = bucket
self.key = key
self.version_id = version_id
# The underlying seekable IO, where all the magic happens
self.raw_stream = _S3SeekableIO(
bucket=bucket,
key=key,
version_id=version_id,
boto3_client=boto3_client,
**sdk_options,
)
# Stores the list of data transformations
self._data_transformations: List[BaseTransform] = []
if is_gzip:
self._data_transformations.append(GzipTransform())
if is_csv:
self._data_transformations.append(CsvTransform())
# Stores the cached transformed stream
self._transformed_stream: Optional[IO[bytes]] = None
def size(self) -> int:
"""
Retrieves the size of the underlying S3 object
"""
return self.raw_stream.size
def transformed_stream(self) -> IO[bytes]:
"""
Returns a IO[bytes] stream with all the data transformations applied in order
"""
if self._transformed_stream is None:
# Create a stream which is the result of applying all the data transformations
# To start with, our transformed stream is the same as our raw seekable stream.
# This means that if there are no data transformations to be applied, IO is just
# delegated directly to the raw_stream.
transformed_stream = self.raw_stream
# Now we apply each transformation in order
# e.g: when self._data_transformations is [transform_1, transform_2], then
# transformed_stream is the equivalent of doing transform_2(transform_1(...(raw_stream)))
for transformation in self._data_transformations:
transformed_stream = transformation.transform(transformed_stream)
self._transformed_stream = transformed_stream
return self._transformed_stream
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]], in_place: Literal[True]) -> T:
pass
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Literal[False],
) -> None:
pass
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]]) -> T:
pass
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Optional[bool] = False,
) -> Optional[T]:
"""
Applies one or more data transformations to the stream.
Parameters
----------
transformations: BaseTransform[T] | Sequence[BaseTransform[T]]
One or more transformations to apply. Transformations are applied in the same order as they are declared.
in_place: bool, optional
Transforms the stream in place, instead of returning a new stream object. Defaults to false.
Returns
-------
T[bound=IO[bytes]], optional
If in_place is False, returns an IO[bytes] object representing the transformed stream
"""
# Make transformations always be a sequence to make mypy happy
if not isinstance(transformations, Sequence):
transformations = [transformations]
# Scenario 1: user wants to transform the stream in place.
# In this case, we store the transformations and invalidate any existing transformed stream.
# This way, the transformed_stream is re-created on the next IO operation.
# This can happen when the user calls .transform multiple times before they start reading data
#
# >>> s3object.transform(GzipTransform(), in_place=True)
# >>> s3object.seek(0, io.SEEK_SET) <- this creates a transformed stream
# >>> s3object.transform(CsvTransform(), in_place=True) <- need to re-create transformed stream
# >>> s3object.read...
if in_place:
self._data_transformations.extend(transformations)
# Invalidate any existing transformed stream.
# It will be created again next time it's accessed.
self._transformed_stream = None
return None
else:
# Tell mypy that raw_stream actually implements T (bound to IO[bytes])
stream = cast(T, self.raw_stream)
for transformation in transformations:
stream = transformation.transform(stream)
return stream
# From this point on, we're just implementing all the standard methods on the IO[bytes] type.
# There's no magic here, just delegating all the calls to our transformed_stream.
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
return self.transformed_stream.seek(offset, whence)
def seekable(self) -> bool:
return self.transformed_stream.seekable()
def readable(self) -> bool:
return self.transformed_stream.readable()
def writable(self) -> bool:
return self.transformed_stream.writable()
def tell(self) -> int:
return self.transformed_stream.tell()
def closed(self) -> bool:
return self.transformed_stream.closed
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def close(self):
# Scenario 1: S3Object = SeekableIO, because there are no data transformations applied
# In this scenario, we can only close the raw_stream. If we tried to also close the transformed_stream we would
# get an error, since they are the same object, and we can't close the same stream twice.
self.raw_stream.close()
# Scenario 2: S3Object -> [Transformations] -> SeekableIO, because there are data transformations applied
# In this scenario, we also need to close the transformed_stream if it exists. The reason we test for
# existence is that the user might want to close the object without reading data from it. Example:
#
# >>> s3object = S3Object(...., is_gzip=True)
# >>> s3object.close() <- transformed_stream doesn't exist yet at this point
if self.raw_stream != self._transformed_stream and self._transformed_stream is not None:
self._transformed_stream.close()
def read(self, size: int = -1) -> bytes:
return self.transformed_stream.read(size)
def readline(self, size: Optional[int] = -1) -> bytes:
return self.transformed_stream.readline()
def readlines(self, hint: int = -1) -> List[bytes]:
return self.transformed_stream.readlines(hint)
def __next__(self):
return self.transformed_stream.__next__()
def __iter__(self):
return self.transformed_stream.__iter__()
def fileno(self) -> int:
raise NotImplementedError("this stream is not backed by a file descriptor")
def flush(self) -> None:
raise NotImplementedError("this stream is not writable")
def isatty(self) -> bool:
return False
def truncate(self, size: Optional[int] = 0) -> int:
raise NotImplementedError("this stream is not writable")
def write(self, data: Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]) -> int:
raise NotImplementedError("this stream is not writable")
def writelines(
self,
data: Iterable[Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]],
) -> None:
raise NotImplementedError("this stream is not writable")
def lambda_handler(event: Dict[str, str], context: LambdaContext):
sample_csv = S3Object(bucket=event["bucket"], key=event["key"])
# Skip the header line
sample_csv.seek(HEADER_SIZE, io.SEEK_SET)
# Jump 100 lines of 9 bytes each (8 bytes of data + 1 byte newline)
sample_csv.seek(LINES_TO_JUMP * ROW_SIZE, io.SEEK_CUR)
sample_csv.transform(CsvTransform(), in_place=True)
for row in sample_csv:
print(row["reading"]) | null |
5,500 | from typing import Dict
from aws_lambda_powertools.utilities.streaming.s3_object import S3Object
from aws_lambda_powertools.utilities.streaming.transformations import CsvTransform
from aws_lambda_powertools.utilities.typing import LambdaContext
class S3Object(IO[bytes]):
"""
Seekable and streamable S3 Object reader.
S3Object implements the IO[bytes], backed by a seekable S3 streaming.
Parameters
----------
bucket: str
The S3 bucket
key: str
The S3 key
version_id: str, optional
A version ID of the object, when the S3 bucket is versioned
boto3_client: S3Client, optional
An optional boto3 S3 client. If missing, a new one will be created.
is_gzip: bool, optional
Enables the Gunzip data transformation
is_csv: bool, optional
Enables the CSV data transformation
sdk_options: dict, optional
Dictionary of options that will be passed to the S3 Client get_object API call
Example
-------
**Reads a line from an S3, loading as little data as necessary:**
>>> from aws_lambda_powertools.utilities.streaming import S3Object
>>>
>>> line: bytes = S3Object(bucket="bucket", key="key").readline()
>>>
>>> print(line)
"""
def __init__(
self,
bucket: str,
key: str,
version_id: Optional[str] = None,
boto3_client: Optional["Client"] = None,
is_gzip: Optional[bool] = False,
is_csv: Optional[bool] = False,
**sdk_options,
):
self.bucket = bucket
self.key = key
self.version_id = version_id
# The underlying seekable IO, where all the magic happens
self.raw_stream = _S3SeekableIO(
bucket=bucket,
key=key,
version_id=version_id,
boto3_client=boto3_client,
**sdk_options,
)
# Stores the list of data transformations
self._data_transformations: List[BaseTransform] = []
if is_gzip:
self._data_transformations.append(GzipTransform())
if is_csv:
self._data_transformations.append(CsvTransform())
# Stores the cached transformed stream
self._transformed_stream: Optional[IO[bytes]] = None
def size(self) -> int:
"""
Retrieves the size of the underlying S3 object
"""
return self.raw_stream.size
def transformed_stream(self) -> IO[bytes]:
"""
Returns a IO[bytes] stream with all the data transformations applied in order
"""
if self._transformed_stream is None:
# Create a stream which is the result of applying all the data transformations
# To start with, our transformed stream is the same as our raw seekable stream.
# This means that if there are no data transformations to be applied, IO is just
# delegated directly to the raw_stream.
transformed_stream = self.raw_stream
# Now we apply each transformation in order
# e.g: when self._data_transformations is [transform_1, transform_2], then
# transformed_stream is the equivalent of doing transform_2(transform_1(...(raw_stream)))
for transformation in self._data_transformations:
transformed_stream = transformation.transform(transformed_stream)
self._transformed_stream = transformed_stream
return self._transformed_stream
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]], in_place: Literal[True]) -> T:
pass
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Literal[False],
) -> None:
pass
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]]) -> T:
pass
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Optional[bool] = False,
) -> Optional[T]:
"""
Applies one or more data transformations to the stream.
Parameters
----------
transformations: BaseTransform[T] | Sequence[BaseTransform[T]]
One or more transformations to apply. Transformations are applied in the same order as they are declared.
in_place: bool, optional
Transforms the stream in place, instead of returning a new stream object. Defaults to false.
Returns
-------
T[bound=IO[bytes]], optional
If in_place is False, returns an IO[bytes] object representing the transformed stream
"""
# Make transformations always be a sequence to make mypy happy
if not isinstance(transformations, Sequence):
transformations = [transformations]
# Scenario 1: user wants to transform the stream in place.
# In this case, we store the transformations and invalidate any existing transformed stream.
# This way, the transformed_stream is re-created on the next IO operation.
# This can happen when the user calls .transform multiple times before they start reading data
#
# >>> s3object.transform(GzipTransform(), in_place=True)
# >>> s3object.seek(0, io.SEEK_SET) <- this creates a transformed stream
# >>> s3object.transform(CsvTransform(), in_place=True) <- need to re-create transformed stream
# >>> s3object.read...
if in_place:
self._data_transformations.extend(transformations)
# Invalidate any existing transformed stream.
# It will be created again next time it's accessed.
self._transformed_stream = None
return None
else:
# Tell mypy that raw_stream actually implements T (bound to IO[bytes])
stream = cast(T, self.raw_stream)
for transformation in transformations:
stream = transformation.transform(stream)
return stream
# From this point on, we're just implementing all the standard methods on the IO[bytes] type.
# There's no magic here, just delegating all the calls to our transformed_stream.
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
return self.transformed_stream.seek(offset, whence)
def seekable(self) -> bool:
return self.transformed_stream.seekable()
def readable(self) -> bool:
return self.transformed_stream.readable()
def writable(self) -> bool:
return self.transformed_stream.writable()
def tell(self) -> int:
return self.transformed_stream.tell()
def closed(self) -> bool:
return self.transformed_stream.closed
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def close(self):
# Scenario 1: S3Object = SeekableIO, because there are no data transformations applied
# In this scenario, we can only close the raw_stream. If we tried to also close the transformed_stream we would
# get an error, since they are the same object, and we can't close the same stream twice.
self.raw_stream.close()
# Scenario 2: S3Object -> [Transformations] -> SeekableIO, because there are data transformations applied
# In this scenario, we also need to close the transformed_stream if it exists. The reason we test for
# existence is that the user might want to close the object without reading data from it. Example:
#
# >>> s3object = S3Object(...., is_gzip=True)
# >>> s3object.close() <- transformed_stream doesn't exist yet at this point
if self.raw_stream != self._transformed_stream and self._transformed_stream is not None:
self._transformed_stream.close()
def read(self, size: int = -1) -> bytes:
return self.transformed_stream.read(size)
def readline(self, size: Optional[int] = -1) -> bytes:
return self.transformed_stream.readline()
def readlines(self, hint: int = -1) -> List[bytes]:
return self.transformed_stream.readlines(hint)
def __next__(self):
return self.transformed_stream.__next__()
def __iter__(self):
return self.transformed_stream.__iter__()
def fileno(self) -> int:
raise NotImplementedError("this stream is not backed by a file descriptor")
def flush(self) -> None:
raise NotImplementedError("this stream is not writable")
def isatty(self) -> bool:
return False
def truncate(self, size: Optional[int] = 0) -> int:
raise NotImplementedError("this stream is not writable")
def write(self, data: Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]) -> int:
raise NotImplementedError("this stream is not writable")
def writelines(
self,
data: Iterable[Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]],
) -> None:
raise NotImplementedError("this stream is not writable")
def lambda_handler(event: Dict[str, str], context: LambdaContext):
s3 = S3Object(bucket=event["bucket"], key=event["key"])
tsv_stream = s3.transform(CsvTransform(delimiter="\t"))
for obj in tsv_stream:
print(obj) | null |
5,501 | from typing import Dict
from aws_lambda_powertools.utilities.streaming.s3_object import S3Object
from aws_lambda_powertools.utilities.streaming.transformations import (
CsvTransform,
GzipTransform,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
class S3Object(IO[bytes]):
"""
Seekable and streamable S3 Object reader.
S3Object implements the IO[bytes], backed by a seekable S3 streaming.
Parameters
----------
bucket: str
The S3 bucket
key: str
The S3 key
version_id: str, optional
A version ID of the object, when the S3 bucket is versioned
boto3_client: S3Client, optional
An optional boto3 S3 client. If missing, a new one will be created.
is_gzip: bool, optional
Enables the Gunzip data transformation
is_csv: bool, optional
Enables the CSV data transformation
sdk_options: dict, optional
Dictionary of options that will be passed to the S3 Client get_object API call
Example
-------
**Reads a line from an S3, loading as little data as necessary:**
>>> from aws_lambda_powertools.utilities.streaming import S3Object
>>>
>>> line: bytes = S3Object(bucket="bucket", key="key").readline()
>>>
>>> print(line)
"""
def __init__(
self,
bucket: str,
key: str,
version_id: Optional[str] = None,
boto3_client: Optional["Client"] = None,
is_gzip: Optional[bool] = False,
is_csv: Optional[bool] = False,
**sdk_options,
):
self.bucket = bucket
self.key = key
self.version_id = version_id
# The underlying seekable IO, where all the magic happens
self.raw_stream = _S3SeekableIO(
bucket=bucket,
key=key,
version_id=version_id,
boto3_client=boto3_client,
**sdk_options,
)
# Stores the list of data transformations
self._data_transformations: List[BaseTransform] = []
if is_gzip:
self._data_transformations.append(GzipTransform())
if is_csv:
self._data_transformations.append(CsvTransform())
# Stores the cached transformed stream
self._transformed_stream: Optional[IO[bytes]] = None
def size(self) -> int:
"""
Retrieves the size of the underlying S3 object
"""
return self.raw_stream.size
def transformed_stream(self) -> IO[bytes]:
"""
Returns a IO[bytes] stream with all the data transformations applied in order
"""
if self._transformed_stream is None:
# Create a stream which is the result of applying all the data transformations
# To start with, our transformed stream is the same as our raw seekable stream.
# This means that if there are no data transformations to be applied, IO is just
# delegated directly to the raw_stream.
transformed_stream = self.raw_stream
# Now we apply each transformation in order
# e.g: when self._data_transformations is [transform_1, transform_2], then
# transformed_stream is the equivalent of doing transform_2(transform_1(...(raw_stream)))
for transformation in self._data_transformations:
transformed_stream = transformation.transform(transformed_stream)
self._transformed_stream = transformed_stream
return self._transformed_stream
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]], in_place: Literal[True]) -> T:
pass
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Literal[False],
) -> None:
pass
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]]) -> T:
pass
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Optional[bool] = False,
) -> Optional[T]:
"""
Applies one or more data transformations to the stream.
Parameters
----------
transformations: BaseTransform[T] | Sequence[BaseTransform[T]]
One or more transformations to apply. Transformations are applied in the same order as they are declared.
in_place: bool, optional
Transforms the stream in place, instead of returning a new stream object. Defaults to false.
Returns
-------
T[bound=IO[bytes]], optional
If in_place is False, returns an IO[bytes] object representing the transformed stream
"""
# Make transformations always be a sequence to make mypy happy
if not isinstance(transformations, Sequence):
transformations = [transformations]
# Scenario 1: user wants to transform the stream in place.
# In this case, we store the transformations and invalidate any existing transformed stream.
# This way, the transformed_stream is re-created on the next IO operation.
# This can happen when the user calls .transform multiple times before they start reading data
#
# >>> s3object.transform(GzipTransform(), in_place=True)
# >>> s3object.seek(0, io.SEEK_SET) <- this creates a transformed stream
# >>> s3object.transform(CsvTransform(), in_place=True) <- need to re-create transformed stream
# >>> s3object.read...
if in_place:
self._data_transformations.extend(transformations)
# Invalidate any existing transformed stream.
# It will be created again next time it's accessed.
self._transformed_stream = None
return None
else:
# Tell mypy that raw_stream actually implements T (bound to IO[bytes])
stream = cast(T, self.raw_stream)
for transformation in transformations:
stream = transformation.transform(stream)
return stream
# From this point on, we're just implementing all the standard methods on the IO[bytes] type.
# There's no magic here, just delegating all the calls to our transformed_stream.
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
return self.transformed_stream.seek(offset, whence)
def seekable(self) -> bool:
return self.transformed_stream.seekable()
def readable(self) -> bool:
return self.transformed_stream.readable()
def writable(self) -> bool:
return self.transformed_stream.writable()
def tell(self) -> int:
return self.transformed_stream.tell()
def closed(self) -> bool:
return self.transformed_stream.closed
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def close(self):
# Scenario 1: S3Object = SeekableIO, because there are no data transformations applied
# In this scenario, we can only close the raw_stream. If we tried to also close the transformed_stream we would
# get an error, since they are the same object, and we can't close the same stream twice.
self.raw_stream.close()
# Scenario 2: S3Object -> [Transformations] -> SeekableIO, because there are data transformations applied
# In this scenario, we also need to close the transformed_stream if it exists. The reason we test for
# existence is that the user might want to close the object without reading data from it. Example:
#
# >>> s3object = S3Object(...., is_gzip=True)
# >>> s3object.close() <- transformed_stream doesn't exist yet at this point
if self.raw_stream != self._transformed_stream and self._transformed_stream is not None:
self._transformed_stream.close()
def read(self, size: int = -1) -> bytes:
return self.transformed_stream.read(size)
def readline(self, size: Optional[int] = -1) -> bytes:
return self.transformed_stream.readline()
def readlines(self, hint: int = -1) -> List[bytes]:
return self.transformed_stream.readlines(hint)
def __next__(self):
return self.transformed_stream.__next__()
def __iter__(self):
return self.transformed_stream.__iter__()
def fileno(self) -> int:
raise NotImplementedError("this stream is not backed by a file descriptor")
def flush(self) -> None:
raise NotImplementedError("this stream is not writable")
def isatty(self) -> bool:
return False
def truncate(self, size: Optional[int] = 0) -> int:
raise NotImplementedError("this stream is not writable")
def write(self, data: Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]) -> int:
raise NotImplementedError("this stream is not writable")
def writelines(
self,
data: Iterable[Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]],
) -> None:
raise NotImplementedError("this stream is not writable")
def lambda_handler(event: Dict[str, str], context: LambdaContext):
s3 = S3Object(bucket=event["bucket"], key=event["key"])
s3.transform([GzipTransform(), CsvTransform()], in_place=True)
for line in s3:
print(line) # returns a dict | null |
5,502 | from typing import Dict
from aws_lambda_powertools.utilities.streaming.s3_object import S3Object
from aws_lambda_powertools.utilities.typing import LambdaContext
class S3Object(IO[bytes]):
"""
Seekable and streamable S3 Object reader.
S3Object implements the IO[bytes], backed by a seekable S3 streaming.
Parameters
----------
bucket: str
The S3 bucket
key: str
The S3 key
version_id: str, optional
A version ID of the object, when the S3 bucket is versioned
boto3_client: S3Client, optional
An optional boto3 S3 client. If missing, a new one will be created.
is_gzip: bool, optional
Enables the Gunzip data transformation
is_csv: bool, optional
Enables the CSV data transformation
sdk_options: dict, optional
Dictionary of options that will be passed to the S3 Client get_object API call
Example
-------
**Reads a line from an S3, loading as little data as necessary:**
>>> from aws_lambda_powertools.utilities.streaming import S3Object
>>>
>>> line: bytes = S3Object(bucket="bucket", key="key").readline()
>>>
>>> print(line)
"""
def __init__(
self,
bucket: str,
key: str,
version_id: Optional[str] = None,
boto3_client: Optional["Client"] = None,
is_gzip: Optional[bool] = False,
is_csv: Optional[bool] = False,
**sdk_options,
):
self.bucket = bucket
self.key = key
self.version_id = version_id
# The underlying seekable IO, where all the magic happens
self.raw_stream = _S3SeekableIO(
bucket=bucket,
key=key,
version_id=version_id,
boto3_client=boto3_client,
**sdk_options,
)
# Stores the list of data transformations
self._data_transformations: List[BaseTransform] = []
if is_gzip:
self._data_transformations.append(GzipTransform())
if is_csv:
self._data_transformations.append(CsvTransform())
# Stores the cached transformed stream
self._transformed_stream: Optional[IO[bytes]] = None
def size(self) -> int:
"""
Retrieves the size of the underlying S3 object
"""
return self.raw_stream.size
def transformed_stream(self) -> IO[bytes]:
"""
Returns a IO[bytes] stream with all the data transformations applied in order
"""
if self._transformed_stream is None:
# Create a stream which is the result of applying all the data transformations
# To start with, our transformed stream is the same as our raw seekable stream.
# This means that if there are no data transformations to be applied, IO is just
# delegated directly to the raw_stream.
transformed_stream = self.raw_stream
# Now we apply each transformation in order
# e.g: when self._data_transformations is [transform_1, transform_2], then
# transformed_stream is the equivalent of doing transform_2(transform_1(...(raw_stream)))
for transformation in self._data_transformations:
transformed_stream = transformation.transform(transformed_stream)
self._transformed_stream = transformed_stream
return self._transformed_stream
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]], in_place: Literal[True]) -> T:
pass
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Literal[False],
) -> None:
pass
def transform(self, transformations: BaseTransform[T] | Sequence[BaseTransform[T]]) -> T:
pass
def transform(
self,
transformations: BaseTransform[T] | Sequence[BaseTransform[T]],
in_place: Optional[bool] = False,
) -> Optional[T]:
"""
Applies one or more data transformations to the stream.
Parameters
----------
transformations: BaseTransform[T] | Sequence[BaseTransform[T]]
One or more transformations to apply. Transformations are applied in the same order as they are declared.
in_place: bool, optional
Transforms the stream in place, instead of returning a new stream object. Defaults to false.
Returns
-------
T[bound=IO[bytes]], optional
If in_place is False, returns an IO[bytes] object representing the transformed stream
"""
# Make transformations always be a sequence to make mypy happy
if not isinstance(transformations, Sequence):
transformations = [transformations]
# Scenario 1: user wants to transform the stream in place.
# In this case, we store the transformations and invalidate any existing transformed stream.
# This way, the transformed_stream is re-created on the next IO operation.
# This can happen when the user calls .transform multiple times before they start reading data
#
# >>> s3object.transform(GzipTransform(), in_place=True)
# >>> s3object.seek(0, io.SEEK_SET) <- this creates a transformed stream
# >>> s3object.transform(CsvTransform(), in_place=True) <- need to re-create transformed stream
# >>> s3object.read...
if in_place:
self._data_transformations.extend(transformations)
# Invalidate any existing transformed stream.
# It will be created again next time it's accessed.
self._transformed_stream = None
return None
else:
# Tell mypy that raw_stream actually implements T (bound to IO[bytes])
stream = cast(T, self.raw_stream)
for transformation in transformations:
stream = transformation.transform(stream)
return stream
# From this point on, we're just implementing all the standard methods on the IO[bytes] type.
# There's no magic here, just delegating all the calls to our transformed_stream.
def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
return self.transformed_stream.seek(offset, whence)
def seekable(self) -> bool:
return self.transformed_stream.seekable()
def readable(self) -> bool:
return self.transformed_stream.readable()
def writable(self) -> bool:
return self.transformed_stream.writable()
def tell(self) -> int:
return self.transformed_stream.tell()
def closed(self) -> bool:
return self.transformed_stream.closed
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def close(self):
# Scenario 1: S3Object = SeekableIO, because there are no data transformations applied
# In this scenario, we can only close the raw_stream. If we tried to also close the transformed_stream we would
# get an error, since they are the same object, and we can't close the same stream twice.
self.raw_stream.close()
# Scenario 2: S3Object -> [Transformations] -> SeekableIO, because there are data transformations applied
# In this scenario, we also need to close the transformed_stream if it exists. The reason we test for
# existence is that the user might want to close the object without reading data from it. Example:
#
# >>> s3object = S3Object(...., is_gzip=True)
# >>> s3object.close() <- transformed_stream doesn't exist yet at this point
if self.raw_stream != self._transformed_stream and self._transformed_stream is not None:
self._transformed_stream.close()
def read(self, size: int = -1) -> bytes:
return self.transformed_stream.read(size)
def readline(self, size: Optional[int] = -1) -> bytes:
return self.transformed_stream.readline()
def readlines(self, hint: int = -1) -> List[bytes]:
return self.transformed_stream.readlines(hint)
def __next__(self):
return self.transformed_stream.__next__()
def __iter__(self):
return self.transformed_stream.__iter__()
def fileno(self) -> int:
raise NotImplementedError("this stream is not backed by a file descriptor")
def flush(self) -> None:
raise NotImplementedError("this stream is not writable")
def isatty(self) -> bool:
return False
def truncate(self, size: Optional[int] = 0) -> int:
raise NotImplementedError("this stream is not writable")
def write(self, data: Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]) -> int:
raise NotImplementedError("this stream is not writable")
def writelines(
self,
data: Iterable[Union[bytes, Union[bytearray, memoryview, Sequence[Any], "mmap", "_CData"]]],
) -> None:
raise NotImplementedError("this stream is not writable")
def lambda_handler(event: Dict[str, str], context: LambdaContext):
s3 = S3Object(bucket=event["bucket"], key=event["key"], version_id=event["version_id"])
for line in s3:
print(line) | null |
5,503 | from __future__ import annotations
from aws_lambda_powertools import Logger
from aws_lambda_powertools.utilities.jmespath_utils import (
envelopes,
extract_data_from_envelope,
)
from aws_lambda_powertools.utilities.typing import LambdaContext
logger = Logger()
def extract_data_from_envelope(data: Union[Dict, str], envelope: str, jmespath_options: Optional[Dict] = None) -> Any:
"""Searches and extracts data using JMESPath
Envelope being the JMESPath expression to extract the data you're after
Built-in JMESPath functions include: powertools_json, powertools_base64, powertools_base64_gzip
Examples
--------
**Deserialize JSON string and extracts data from body key**
from aws_lambda_powertools.utilities.jmespath_utils import extract_data_from_envelope
from aws_lambda_powertools.utilities.typing import LambdaContext
def handler(event: dict, context: LambdaContext):
# event = {"body": "{\"customerId\":\"dd4649e6-2484-4993-acb8-0f9123103394\"}"} # noqa: ERA001
payload = extract_data_from_envelope(data=event, envelope="powertools_json(body)")
customer = payload.get("customerId") # now deserialized
...
Parameters
----------
data : Dict
Data set to be filtered
envelope : str
JMESPath expression to filter data against
jmespath_options : Dict
Alternative JMESPath options to be included when filtering expr
Returns
-------
Any
Data found using JMESPath expression given in envelope
"""
if not jmespath_options:
jmespath_options = {"custom_functions": PowertoolsFunctions()}
try:
logger.debug(f"Envelope detected: {envelope}. JMESPath options: {jmespath_options}")
return jmespath.search(envelope, data, options=jmespath.Options(**jmespath_options))
except (LexerError, TypeError, UnicodeError) as e:
message = f"Failed to unwrap event from envelope using expression. Error: {e} Exp: {envelope}, Data: {data}" # noqa: B306, E501
raise InvalidEnvelopeExpressionError(message)
def handler(event: dict, context: LambdaContext) -> dict:
records: list = extract_data_from_envelope(data=event, envelope=envelopes.SQS)
for record in records: # records is a list
logger.info(record.get("customerId")) # now deserialized
return {"message": "success", "statusCode": 200} | null |
5,504 | import json
from dataclasses import asdict, dataclass, field, is_dataclass
from uuid import uuid4
import powertools_json_jmespath_schema as schemas
from jmespath.exceptions import JMESPathTypeError
from aws_lambda_powertools.utilities.typing import LambdaContext
from aws_lambda_powertools.utilities.validation import SchemaValidationError, validate
class Order:
user_id: int
product_id: int
quantity: int
price: float
currency: str
order_id: str = field(default_factory=lambda: f"{uuid4()}")
class DataclassCustomEncoder(json.JSONEncoder):
"""A custom JSON encoder to serialize dataclass obj"""
def default(self, obj):
# Only called for values that aren't JSON serializable
# where `obj` will be an instance of Order in this example
return asdict(obj) if is_dataclass(obj) else super().default(obj)
def return_error_message(message: str) -> dict:
return {"order": None, "message": message, "success": False}
def lambda_handler(event, context: LambdaContext) -> dict:
try:
# Validate order against our schema
validate(event=event, schema=schemas.INPUT, envelope="powertools_json(payload)")
# Deserialize JSON string order as dict
# alternatively, extract_data_from_envelope works here too
order_payload: dict = json.loads(event.get("payload"))
return {
"order": json.dumps(Order(**order_payload), cls=DataclassCustomEncoder),
"message": "order created",
"success": True,
}
except JMESPathTypeError:
# The powertools_json() envelope function must match a valid path
return return_error_message("Invalid request.")
except SchemaValidationError as exception:
# SchemaValidationError indicates where a data mismatch is
return return_error_message(str(exception))
except json.JSONDecodeError:
return return_error_message("Payload must be valid JSON (base64 encoded).") | null |
5,505 | from aws_lambda_powertools.utilities.jmespath_utils import extract_data_from_envelope
from aws_lambda_powertools.utilities.typing import LambdaContext
def extract_data_from_envelope(data: Union[Dict, str], envelope: str, jmespath_options: Optional[Dict] = None) -> Any:
"""Searches and extracts data using JMESPath
Envelope being the JMESPath expression to extract the data you're after
Built-in JMESPath functions include: powertools_json, powertools_base64, powertools_base64_gzip
Examples
--------
**Deserialize JSON string and extracts data from body key**
from aws_lambda_powertools.utilities.jmespath_utils import extract_data_from_envelope
from aws_lambda_powertools.utilities.typing import LambdaContext
def handler(event: dict, context: LambdaContext):
# event = {"body": "{\"customerId\":\"dd4649e6-2484-4993-acb8-0f9123103394\"}"} # noqa: ERA001
payload = extract_data_from_envelope(data=event, envelope="powertools_json(body)")
customer = payload.get("customerId") # now deserialized
...
Parameters
----------
data : Dict
Data set to be filtered
envelope : str
JMESPath expression to filter data against
jmespath_options : Dict
Alternative JMESPath options to be included when filtering expr
Returns
-------
Any
Data found using JMESPath expression given in envelope
"""
if not jmespath_options:
jmespath_options = {"custom_functions": PowertoolsFunctions()}
try:
logger.debug(f"Envelope detected: {envelope}. JMESPath options: {jmespath_options}")
return jmespath.search(envelope, data, options=jmespath.Options(**jmespath_options))
except (LexerError, TypeError, UnicodeError) as e:
message = f"Failed to unwrap event from envelope using expression. Error: {e} Exp: {envelope}, Data: {data}" # noqa: B306, E501
raise InvalidEnvelopeExpressionError(message)
def handler(event: dict, context: LambdaContext) -> dict:
payload = extract_data_from_envelope(data=event, envelope="powertools_json(body)")
customer_id = payload.get("customerId") # now deserialized
# also works for fetching and flattening deeply nested data
some_data = extract_data_from_envelope(data=event, envelope="deeply_nested[*].some_data[]")
return {"customer_id": customer_id, "message": "success", "context": some_data, "statusCode": 200} | null |
5,506 | import base64
import binascii
import gzip
import json
import powertools_base64_gzip_jmespath_schema as schemas
from jmespath.exceptions import JMESPathTypeError
from aws_lambda_powertools.utilities.typing import LambdaContext
from aws_lambda_powertools.utilities.validation import SchemaValidationError, validate
def return_error_message(message: str) -> dict:
return {"message": message, "success": False}
def lambda_handler(event, context: LambdaContext) -> dict:
try:
validate(event=event, schema=schemas.INPUT, envelope="powertools_base64_gzip(payload) | powertools_json(@)")
# Alternatively, extract_data_from_envelope works here too
encoded_payload = base64.b64decode(event["payload"])
uncompressed_payload = gzip.decompress(encoded_payload).decode()
log: dict = json.loads(uncompressed_payload)
return {
"message": "Logs processed",
"log_group": log.get("logGroup"),
"owner": log.get("owner"),
"success": True,
}
except JMESPathTypeError:
return return_error_message("The powertools_base64_gzip() envelope function must match a valid path.")
except binascii.Error:
return return_error_message("Payload must be a valid base64 encoded string")
except json.JSONDecodeError:
return return_error_message("Payload must be valid JSON (base64 encoded).")
except SchemaValidationError as exception:
# SchemaValidationError indicates where a data mismatch is
return return_error_message(str(exception)) | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.