# -*- coding: utf-8 -*- from werkzeug.wrappers import Response from werkzeug.datastructures import Headers from gzip import GzipFile import simplejson as json import gzip try: from cStringIO import StringIO as IO except ImportError: from StringIO import StringIO as IO GZIP_COMPRESSION_LEVEL = 9 ''' Make JSON response ''' def make_json_response(data=None, status=200): return Response(json.dumps(data), status=status, content_type='application/json') ''' Make GZIP to JSON response ''' def make_gzip_response(data=None, status=200): gzip_buffer = IO() with GzipFile(mode='wb', compresslevel=GZIP_COMPRESSION_LEVEL, fileobj=gzip_buffer) as gzip_file: gzip_file.write(json.dumps(data)) contents = gzip_buffer.getvalue() gzip_buffer.close() headers = Headers() headers.add('Content-Encoding', 'gzip') headers.add('Vary', 'Accept-Encoding') headers.add('Content-Length', len(contents)) return Response(contents, status=status, headers=headers, content_type='application/json')