Skip to content

Instantly share code, notes, and snippets.

@a-hisame
Created December 7, 2016 13:13
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 a-hisame/17ceea787d344477193a47f282b716a4 to your computer and use it in GitHub Desktop.
Save a-hisame/17ceea787d344477193a47f282b716a4 to your computer and use it in GitHub Desktop.
Example: Utility Responses on Python bottle
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import datetime
import zipfile
import io
from bottle import HTTPResponse
def json_response(obj, none_is_error=True, default=lambda o: o):
if (obj is None) and none_is_error:
r = HTTPResponse(status=404, body=json.dumps({'error': 'resource not found'}, default=default))
else:
r = HTTPResponse(status=200, body=json.dumps(obj, default=default))
r.set_header('Content-Type', 'application/json')
return r
def csv_response(rows, default_filename):
csvfile = u'\n'.join([ u','.join([ u'"{0}"'.format(column) for column in row ]) for row in rows ])
r = HTTPResponse(status=200, body=csvfile)
r.set_header('Content-Type', 'application/octet-stream')
r.set_header('Content-Disposition', u"attachment; filename='{0}'".format(default_filename))
return r
def zipped_csv_response(rows, csv_filename):
csvfile = u'\n'.join([ u','.join([ u'"{0}"'.format(column) for column in row ]) for row in rows ])
buf = io.BytesIO()
with zipfile.ZipFile(buf, 'w') as zipfh:
dt = datetime.datetime.now()
timeinfo = (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
info = zipfile.ZipInfo(csv_filename, timeinfo)
info.compress_type = zipfile.ZIP_DEFLATED
zipfh.writestr(info, csvfile)
buf.seek(0)
r = HTTPResponse(status=200, body=buf)
r.set_header('Content-Type', 'application/zip')
r.set_header('Content-Disposition', u"attachment; filename='{0}.zip'".format(csv_filename))
return r
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment