2 Define special types used in BlueChips
5 import sqlalchemy as sa
6 from bluechips.lib.subclass import SmartSubclass
8 class Currency(object):
9 __metaclass__ = SmartSubclass(int)
10 def __init__(self, value):
11 if isinstance(value, str):
12 self.value = int(float(value) * 100)
14 self.value = int(value)
19 return float(self.value)
21 return long(self.value)
23 def __cmp__(self, other):
25 return self.value.__cmp__(int(other))
27 return self.value.__cmp__(0)
29 def __mul__(self, other):
30 return Currency(self.value * other)
31 def __rmul__(self, other):
32 return self.__mul__(other)
34 def __str_no_dollar__(self):
38 return '%s("%s")' % (self.__class__.__name__, str(self))
40 sign = '-' if self.value < 0 else ''
41 cents = abs(self.value) % 100
42 dollars = (abs(self.value) - cents) / 100
43 return '$%s%s.%.02d' % (sign, dollars, cents)
45 class DBCurrency(sa.types.TypeDecorator):
47 A type which represents monetary amounts internally as integers.
49 This avoids binary/decimal float conversion issues
52 impl = sa.types.Integer
54 def process_bind_param(self, value, engine):
57 def convert_result_value(self, value, engine):
58 return Currency(value)