Last active
August 29, 2015 14:03
-
-
Save kageurufu/c6db8708f9532ee8e895 to your computer and use it in GitHub Desktop.
Simple data munging for outputting reports
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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