Created
October 24, 2022 23:01
-
-
Save sergiors/b71e0531f8161b1ffbb23c74a6bc57a4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from aws_lambda_powertools.event_handler.api_gateway import Response, content_types | |
import decimal | |
import json | |
from datetime import date, datetime | |
class DecimalEncoder(json.JSONEncoder): | |
def default(self, o): | |
if isinstance(o, decimal.Decimal): | |
if o % 1 > 0: | |
return float(o) | |
return int(o) | |
return super(__class__, self).default(o) | |
class DateTimeEncoder(json.JSONEncoder): | |
def default(self, o): | |
if isinstance(o, datetime): | |
return o.isoformat() | |
if isinstance(o, date): | |
return o.isoformat() | |
return super(__class__, self).default(o) | |
class JSONEncoder(DecimalEncoder, DateTimeEncoder): | |
... | |
class JSONResponse(Response): | |
def __init__( | |
self, | |
body: Any = None, | |
*, | |
status_code: int = HTTPStatus.OK, | |
headers: Optional[dict] = None, | |
) -> None: | |
super().__init__( | |
status_code=status_code, | |
content_type=content_types.APPLICATION_JSON, | |
headers=headers, | |
body=json.dumps( | |
body, | |
cls=JSONEncoder, | |
ensure_ascii=False, | |
allow_nan=False, | |
indent=None, | |
separators=(',', ':'), | |
).encode('utf-8'), | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment