2 Define special types used in BlueChips
5 import sqlalchemy as sa
6 from bluechips.lib.subclass import SmartSubclass
8 class Currency(object):
10 Store currency values as an integral number of cents
12 __metaclass__ = SmartSubclass(int)
13 def __init__(self, value):
14 if isinstance(value, str):
15 self.value = int(float(value) * 100)
17 self.value = int(value)
21 If I don't define this, SmartSubclass will return
22 Currency(int(self.value))
27 If I don't define this, SmartSubclass will return
28 Currency(float(self.value))
30 return float(self.value)
33 If I don't define this, SmartSubclass will return
34 Currency(long(self.value))
36 return long(self.value)
38 def __cmp__(self, other):
40 This is overridden for when validators compare a Currency to
46 return self.value.__cmp__(int(other))
48 def __mul__(self, other):
50 If I don't define this, SmartSubclass will convert the other
53 return Currency(self.value * other)
54 def __rmul__(self, other):
56 If I don't define this, SmartSubclass will convert the other
59 return self.__mul__(other)
61 def __str_no_dollar__(self):
63 Get to the formatted string without the dollar sign
68 return '%s("%s")' % (self.__class__.__name__, str(self))
70 sign = '-' if self.value < 0 else ''
71 cents = abs(self.value) % 100
72 dollars = (abs(self.value) - cents) / 100
73 return '$%s%s.%.02d' % (sign, dollars, cents)
75 class DBCurrency(sa.types.TypeDecorator):
77 A type which represents monetary amounts internally as integers.
79 This avoids binary/decimal float conversion issues
82 impl = sa.types.Integer
84 def process_bind_param(self, value, engine):
87 def convert_result_value(self, value, engine):
88 return Currency(value)