018391f733
Chore: Bumped the version to 3.3
59 lines
1.4 KiB
Python
59 lines
1.4 KiB
Python
import csv
|
|
from decimal import Decimal
|
|
from io import StringIO
|
|
import uuid
|
|
|
|
from pyramid.renderers import JSON
|
|
|
|
|
|
__author__ = 'tanshu'
|
|
|
|
|
|
class CSVRenderer(object):
|
|
def __init__(self, info):
|
|
pass
|
|
|
|
def __call__(self, value, system):
|
|
csv_data = StringIO()
|
|
writer = csv.writer(csv_data, delimiter=',', quoting=csv.QUOTE_MINIMAL)
|
|
|
|
if 'header' in value:
|
|
writer.writerow(value['header'])
|
|
if 'rows' in value:
|
|
writer.writerows(value['rows'])
|
|
if 'footer' in value:
|
|
writer.writerows(value['footer'])
|
|
|
|
request = system.get('request')
|
|
if request is not None:
|
|
response = request.response
|
|
ct = response.content_type
|
|
if ct == response.default_content_type:
|
|
response.content_type = 'text/csv'
|
|
filename = value['filename'] if 'filename' in value else 'report.csv'
|
|
response.content_disposition = 'attachment;filename="{0}"'.format(filename)
|
|
return csv_data.getvalue()
|
|
|
|
|
|
json_renderer = JSON()
|
|
|
|
|
|
class DecimalAsFloatHack(float):
|
|
def __init__(self, d):
|
|
self.d = d
|
|
|
|
def __repr__(self):
|
|
return str(self.d)
|
|
|
|
|
|
def decimal_adaptor(obj, request):
|
|
return DecimalAsFloatHack(obj)
|
|
|
|
|
|
def uuid_adaptor(obj, request):
|
|
return str(obj)
|
|
|
|
|
|
json_renderer.add_adapter(Decimal, decimal_adaptor)
|
|
json_renderer.add_adapter(uuid.UUID, uuid_adaptor)
|