Skip to content

Instantly share code, notes, and snippets.

@jaysonsantos
Last active January 31, 2020 09:57
Show Gist options
  • Save jaysonsantos/5c425683a961a3e8f65146dc04247bc5 to your computer and use it in GitHub Desktop.
Save jaysonsantos/5c425683a961a3e8f65146dc04247bc5 to your computer and use it in GitHub Desktop.
import re
from dataclasses import dataclass, fields
from typing import Dict
CAMEL_CASE_RE = re.compile(r'([a-z])([A-Z])')
@dataclass(frozen=True)
class ApiGatewayRequest:
headers: Dict[str, str]
body: str
path_parameters: Dict[str, str]
@classmethod
def from_dict(cls, dict_) -> "ApiGatewayRequest":
valid_fields = {field.name for field in fields(ApiGatewayRequest)}
converted_dict = {
normalized_key: value
for (key, value) in dict_.items()
if (normalized_key := camel_case_to_snake_case(key)) in valid_fields
}
return ApiGatewayRequest(**converted_dict)
def camel_case_to_snake_case(name: str) -> str:
return CAMEL_CASE_RE.sub(r"\1_\2", name).lower()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment