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

jd. picture jd. · Mar 21, 2014 · Viewed 20.1k times · Source

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.

Answer

Martijn Pieters picture Martijn Pieters · Mar 21, 2014

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')]