Skip to content

Instantly share code, notes, and snippets.

@a-hisame
Created December 7, 2016 13:13
Show Gist options
  • Select an option

  • Save a-hisame/17ceea787d344477193a47f282b716a4 to your computer and use it in GitHub Desktop.

Select an option

Save a-hisame/17ceea787d344477193a47f282b716a4 to your computer and use it in GitHub Desktop.

Revisions

  1. a-hisame created this gist Dec 7, 2016.
    43 changes: 43 additions & 0 deletions response_util.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    #!/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