from datetime import datetime
from flask import json
from accounting import Amount, Transaction, Posting, Account
class AccountingEncoder(json.JSONEncoder):
def default(self, o):
@@ -27,12 +29,17 @@ class AccountingEncoder(json.JSONEncoder):
elif isinstance(o, Amount):
return dict(
__type__=o.__class__.__name__,
amount=o.amount,
symbol=o.symbol
)
elif isinstance(o, Exception):
args=o.args
return json.JSONEncoder.default(self, o)
class AccountingDecoder(json.JSONDecoder):
def __init__(self):
json.JSONDecoder.__init__(self, object_hook=self.dict_to_object)
@@ -43,7 +50,10 @@ class AccountingDecoder(json.JSONDecoder):
types = {c.__name__ : c for c in [Amount, Transaction, Posting,
Account]}
_type = d.pop('__type__')
if _type == 'Transaction':
d['date'] = datetime.strptime(d['date'], '%Y-%m-%d')
return types[_type](**d)