Adding a common moneratary amount field type
This commit is contained in:
0
api/app/core/__init__.py
Normal file
0
api/app/core/__init__.py
Normal file
41
api/app/core/types.py
Normal file
41
api/app/core/types.py
Normal file
@@ -0,0 +1,41 @@
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from pydantic import GetCoreSchemaHandler
|
||||
from pydantic_core import core_schema
|
||||
|
||||
@dataclass
|
||||
class MonetaryAmount:
|
||||
amount: Decimal# = Field(decimal_places=2, default=0)
|
||||
|
||||
@classmethod
|
||||
def __get_pydantic_core_schema__(
|
||||
cls, source: type[Any], handler: GetCoreSchemaHandler
|
||||
) -> core_schema.CoreSchema:
|
||||
assert source is MonetaryAmount
|
||||
return core_schema.no_info_after_validator_function(
|
||||
cls._validate,
|
||||
core_schema.float_schema(multiple_of=0.01),
|
||||
serialization=core_schema.plain_serializer_function_ser_schema(
|
||||
cls._serialize,
|
||||
info_arg=False,
|
||||
return_schema=core_schema.float_schema(multiple_of=0.01),
|
||||
),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _validate(value: str) -> 'CompressedString':
|
||||
inverse_dictionary: dict[str, int] = {}
|
||||
text: list[int] = []
|
||||
for word in value.split(' '):
|
||||
if word not in inverse_dictionary:
|
||||
inverse_dictionary[word] = len(inverse_dictionary)
|
||||
text.append(inverse_dictionary[word])
|
||||
return MonetaryAmount(
|
||||
{v: k for k, v in inverse_dictionary.items()}, text
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _serialize(value: 'CompressedString') -> str:
|
||||
return value.amount
|
||||
Reference in New Issue
Block a user