Flask: 'Response' object is not iterable with response-producing exceptions

23,401

jsonify() produces a full response object, not a response body, so use HTTPException.get_response(), not .get_body():

class JSONException(HTTPException):    
    def get_response(self, environ):
        return jsonify(a=1)

The alternative is to just use json.dumps() to produce a body here:

class JSONException(HTTPException):
    def get_body(self, environ):
        return json.dumps({a: 1})

    def get_headers(self, environ):
        return [('Content-Type', 'application/json')]
Share:
23,401
jd.
Author by

jd.

Python and JavaScript developer. Full-stack web programming, web scraping, databases, devops.

Updated on March 22, 2020

Comments

  • jd.
    jd. about 4 years

    I can't seem to generate responses from exceptions anymore in Flask 0.10.1 (the same happened with 0.9). This code:

    from flask import Flask, jsonify
    from werkzeug.exceptions import HTTPException
    import flask, werkzeug
    
    print 'Flask version: %s' % flask.__version__
    print 'Werkzeug version: %s' % werkzeug.__version__
    
    app = Flask(__name__)
    app.config['PROPAGATE_EXCEPTIONS'] = True
    
    class JSONException(HTTPException):
        response = None
    
        def get_body(self, environ):
            return jsonify(a=1)
    
        def get_headers(self, environ):
            return [('Content-Type', 'application/json')]
    
    @app.route('/x')
    def x():
        return jsonify(a=1)
    
    @app.route('/y')
    def y():
        raise JSONException()
    
    c = app.test_client()
    r = c.get('x')
    print r.data
    r = c.get('y')
    print r.data
    

    prints

    Flask version: 0.10.1
    Werkzeug version: 0.9.4
    {
      "a": 1
    }
    Traceback (most recent call last):
      File "flask_error.py", line 33, in <module>
        print r.data
      File "/home/path/lib/python2.7/site-packages/werkzeug/wrappers.py", line 881, in get_data
        self._ensure_sequence()
      File "/home/path/lib/python2.7/site-packages/werkzeug/wrappers.py", line 938, in _ensure_sequence
        self.make_sequence()
      File "/home/path/lib/python2.7/site-packages/werkzeug/wrappers.py", line 953, in make_sequence
        self.response = list(self.iter_encoded())
      File "/home/path/lib/python2.7/site-packages/werkzeug/wrappers.py", line 81, in _iter_encoded
        for item in iterable:
      File "/home/path/lib/python2.7/site-packages/werkzeug/wsgi.py", line 682, in __next__
        return self._next()
      File "/home/path/lib/python2.7/site-packages/werkzeug/wrappers.py", line 81, in _iter_encoded
        for item in iterable:
      File "/home/path/lib/python2.7/site-packages/werkzeug/wsgi.py", line 682, in __next__
        return self._next()
      File "/home/path/lib/python2.7/site-packages/werkzeug/wrappers.py", line 81, in _iter_encoded
        for item in iterable:
    TypeError: 'Response' object is not iterable
    

    The traceback is unexpected.

  • szeitlin
    szeitlin almost 9 years
    I just tried this, and got "RuntimeError: working outside of application context" with regard to jsonify (?).
  • Martijn Pieters
    Martijn Pieters almost 9 years
    @szeitlin: so where are you raising the exception and where are you handling it?