marco@16: #!/usr/bin/env python marco@16: # -*- coding: utf-8 -*- marco@16: marco@16: """ marco@16: Provides a class to hold the `sword2.Connection` transaction history and give simple means for export (JSON) and reporting. marco@16: """ marco@16: marco@16: from sword2_logging import logging marco@16: marco@16: from datetime import datetime marco@16: marco@16: th_l = logging.getLogger(__name__) marco@16: marco@16: class Transaction_History(list): marco@16: def log(self, event_type, **kw): marco@16: self.append({'type':event_type, marco@16: 'timestamp':datetime.now().isoformat(), marco@16: 'payload':kw}) marco@16: marco@16: def __str__(self): marco@16: _s = [] marco@16: for item in self: marco@16: _s.append("-"*20) marco@16: _s.append("Type: '%s' [%s]\nData:" % (item['type'], item['timestamp'])) marco@16: for key, value in item['payload'].iteritems(): marco@16: _s.append("%s: %s" % (key, value)) marco@16: marco@16: return "\n".join(_s) marco@16: marco@16: def to_json(self): marco@16: from compatible_libs import json marco@16: if json: marco@16: th_l.debug("Attempting to dump %s history items to JSON" % len(self)) marco@16: return json.dumps(self) marco@16: else: marco@16: th_l.error("Cannot procede with converting the transaction history to JSON") marco@16: marco@16: def to_pretty_json(self): marco@16: from compatible_libs import json marco@16: if json: marco@16: th_l.debug("Attempting to dump %s history items to indented, readable JSON" % len(self)) marco@16: return json.dumps(self, indent=True) marco@16: else: marco@16: th_l.error("Cannot procede with converting the transaction history to JSON") marco@16: