Created
November 16, 2018 18:26
-
-
Save josegomezr/da4ffde6ab9b89c1c88430839b53fc31 to your computer and use it in GitHub Desktop.
SatoshiField implementation
This file contains 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
import decimal | |
class Satoshify(object): | |
'''Helper class to convert from "satoshi" notation to decimal notation.''' | |
DECIMAL_PLACES = 8 | |
DIVISOR = 10**DECIMAL_PLACES | |
@classmethod | |
def to_sats(cls, num): | |
return num * cls.DIVISOR | |
@classmethod | |
def from_sats(cls, num): | |
c = decimal.Context(prec=cls.DECIMAL_PLACES) | |
n = decimal.Decimal(num, c) / cls.DIVISOR | |
return n | |
class BaseSatoshiField(object): | |
def __init__(self, attr, *args, **kwargs): | |
self.attr = attr | |
def to_property(self, **kwargs): | |
getter = self.make_getter() | |
setter = None | |
deleter = None | |
docstring = None | |
if kwargs.get('setter', True): | |
setter = self.make_setter() | |
if kwargs.get('deleter', True): | |
deleter = None | |
docstring = kwargs.get('doc') | |
funcs = [getter, setter, deleter, docstring] | |
return property(*funcs) | |
def make_getter(self): | |
def wrapped_getter(newself): | |
orig = getattr(newself, self.attr) | |
return Satoshify.from_sats(orig) | |
return wrapped_getter | |
def make_setter(self): | |
def wrapped_setter(newself, orig): | |
value = Satoshify.to_sats(orig) | |
setattr(newself, self.attr, value) | |
return wrapped_setter | |
def getter(self, newself): | |
call = self.make_getter() | |
return call(newself) | |
def setter(self, newself, value): | |
call = self.make_setter() | |
return call(newself, value) | |
def SatoshiField(attrib, **kwargs): | |
''' | |
Returns a *virtual* 'dependant' Django field that converts from satoshis | |
(original field) to decimal notation. | |
Usage: | |
# Your model fields... resumed for brevity | |
satoshis = models.BigIntegerField(default=0) | |
coins = SatoshiField('satoshis') | |
# --- | |
model.satoshis = 1000 | |
print(model.coins) # prints 0.0001000 | |
model.coins = 0.5 | |
print(model.satoshis) # prints 50000000 | |
''' | |
return BaseSatoshiField(attrib).to_property(**kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment