Last active
December 5, 2019 14:12
-
-
Save valdergallo/eb65dbaf9134a848cc8a5715f854eaea to your computer and use it in GitHub Desktop.
Gerencianet integration with mashmellow schema
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
# -*- coding: utf-8 -*- | |
from string import ascii_letters, punctuation | |
from marshmallow import fields | |
from decimal import Decimal | |
punctuation_without_subtract = punctuation.replace('-', '') | |
STRIP_LETTERS = punctuation_without_subtract + ascii_letters | |
def _strip_values(value): | |
return str(value).translate( | |
str.maketrans('', '', STRIP_LETTERS)) | |
def encode(value): | |
"Encode float/decimal values to gerencianet int" | |
str_value = _strip_values(value) | |
if not str_value: | |
return 0 | |
return int(str_value) | |
def decode(value): | |
"Decode gerencianet int to decimal" | |
str_value = _strip_values(value) | |
fix_2_points = str_value[-2:] | |
fix_body = str_value[:-2] | |
if not fix_2_points: | |
fix_2_points = '00' | |
if not fix_body: | |
fix_body = '0' | |
return Decimal(fix_body + '.' + fix_2_points) | |
class GerencianetDecimalField(fields.Decimal): | |
def _serialize(self, value, attr, obj, **kwargs): | |
return encode(value) | |
def _deserialize(self, value, attr, data, **kwargs): | |
return decode(value) | |
class GerencianetFloatField(fields.Float): | |
def _serialize(self, value, attr, obj, **kwargs): | |
return encode(value) | |
def _deserialize(self, value, attr, data, **kwargs): | |
return float(decode(value).to_eng_string()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment