representations.py 850 B

1234567891011121314151617181920212223242526272829
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals, absolute_import
  3. try:
  4. from ujson import dumps
  5. except ImportError:
  6. from json import dumps
  7. from flask import make_response, current_app
  8. def output_json(data, code, headers=None):
  9. """Makes a Flask response with a JSON encoded body"""
  10. settings = current_app.config.get("RESTX_JSON", {})
  11. # If we're in debug mode, and the indent is not set, we set it to a
  12. # reasonable value here. Note that this won't override any existing value
  13. # that was set.
  14. if current_app.debug:
  15. settings.setdefault("indent", 4)
  16. # always end the json dumps with a new line
  17. # see https://github.com/mitsuhiko/flask/pull/1262
  18. dumped = dumps(data, **settings) + "\n"
  19. resp = make_response(dumped, code)
  20. resp.headers.extend(headers or {})
  21. return resp