http_response.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. # -*- coding: utf-8 -*-
  2. from werkzeug.wrappers import Response
  3. from werkzeug.datastructures import Headers
  4. from gzip import GzipFile
  5. import simplejson as json
  6. import gzip
  7. try:
  8. from cStringIO import StringIO as IO
  9. except ImportError:
  10. from StringIO import StringIO as IO
  11. GZIP_COMPRESSION_LEVEL = 9
  12. '''
  13. Make JSON response
  14. '''
  15. def make_json_response(data=None, status=200):
  16. return Response(json.dumps(data), status=status, content_type='application/json')
  17. '''
  18. Make GZIP to JSON response
  19. '''
  20. def make_gzip_response(data=None, status=200):
  21. gzip_buffer = IO()
  22. with GzipFile(mode='wb', compresslevel=GZIP_COMPRESSION_LEVEL, fileobj=gzip_buffer) as gzip_file:
  23. gzip_file.write(json.dumps(data))
  24. contents = gzip_buffer.getvalue()
  25. gzip_buffer.close()
  26. headers = Headers()
  27. headers.add('Content-Encoding', 'gzip')
  28. headers.add('Vary', 'Accept-Encoding')
  29. headers.add('Content-Length', len(contents))
  30. return Response(contents, status=status, headers=headers, content_type='application/json')