Chris
Chris

Reputation: 7310

Flask error handling: "Response object is not iterable"

I'm trying to set of a REST web service using Flask. I'm having a problem with the error handling @app.errorhandler(404)

#!flask/bin/python
from flask import Flask, jsonify, abort

app = Flask(__name__)

@app.errorhandler(404)
def not_found(error):
    return jsonify({'error':'not found'}), 404

if __name__ == '__main__':
app.run(debug = True)

When I cURL it, I get nothing. In my debugger, it's telling me I have a TypeError: 'Response' object is not iterable

I used jsonify in another method with a dictionary with no problem, but when I return it as an error, it doesn't work. Any ideas?

Upvotes: 7

Views: 10832

Answers (2)

Matt Good
Matt Good

Reputation: 3127

As mentioned in the comments for the previous answer, that code isn't supported on Flask 0.8, and would require 0.9 or higher. If you need to support Flask 0.8, here is a compatible version that assigns the "status_code" instead:

@app.errorhandler(404)
def not_found(error):
    resp = jsonify({'error':'not found'})
    resp.status_code = 404
    return resp

Upvotes: 4

falsetru
falsetru

Reputation: 369394

from flask import Flask, jsonify

app = Flask(__name__)

@app.errorhandler(404)
def not_found(error):
    return jsonify({'error':'not found'}), 404

app.run()

With code above, curl http://localhost:5000/ give me:

{
  "error": "not found"
}

Are you using flask.jsonify?

Upvotes: 10

Related Questions