json.py 873 B

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