Skip to content

Instantly share code, notes, and snippets.

@kageurufu
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kageurufu/c6db8708f9532ee8e895 to your computer and use it in GitHub Desktop.
Save kageurufu/c6db8708f9532ee8e895 to your computer and use it in GitHub Desktop.
Simple data munging for outputting reports
import csv
from StringIO import StringIO
def rec_getattr(obj, attr, default=None):
"""Get object's attribute. May use dot notation.
>>> class C(object): pass
>>> a = C()
>>> a.b = C()
>>> a.b.c = 4
>>> rec_getattr(a, 'b.c')
4
"""
if '.' not in attr:
return getattr(obj, attr, default)
else:
A, L = attr.split('.', 1)
return rec_getattr(getattr(obj, A, default), L, default)
class Report(object):
data = None
def __init__(self, objects, columns, headings=None):
if headings and len(columns) != len(headings):
raise ValueError("columns and headings must have the same number of entries")
self.data = []
self.columns = columns
self.headings = headings and headings or columns
self.objects = objects
for object in self.objects:
row = []
for column in iter(self.columns):
row.append(rec_getattr(object, column, None))
self.data.append(row)
@property
def as_csv(self):
csv_file = StringIO()
writer = csv.writer(csv_file, dialect="excel", quoting=csv.QUOTE_NONNUMERIC, lineterminator="\n")
writer.writerow(self.headings)
for row in self.data:
writer.writerow(row)
return csv_file.getvalue()
@property
def as_json(self):
results = []
for row in self.data:
results.append(dict(zip(self.headings, row)))
return results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment