Skip to content

Instantly share code, notes, and snippets.

@joshourisman
Created October 2, 2009 19:48
Show Gist options
  • Save joshourisman/200041 to your computer and use it in GitHub Desktop.
Save joshourisman/200041 to your computer and use it in GitHub Desktop.
import csv, StringIO
class CSVEmitter(Emitter):
def get_keys(self, input_dict):
keys = []
for item in input_dict.items():
if isinstance(item[1], dict):
keys.extend(self.get_keys(item[1]))
else:
keys.append(item[0])
return keys
def get_values(self, input_dict):
for item in input_dict.items():
if isinstance(item[1], dict):
input_dict.update(self.get_values(input_dict.pop(item[0])))
else:
input_dict[item[0]] = smart_str(item[1])
return input_dict
def render(self, request):
response = StringIO.StringIO()
content = self.construct()
keys = self.get_keys(content[0])
writer = csv.DictWriter(response, keys, dialect='excel')
headers = dict((n,n) for n in keys)
writer.writerow(headers)
for row in content:
writer.writerow(self.get_values(row))
return response
Emitter.register('csv', CSVEmitter, 'application/csv; charset=utf-8')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment