Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 267
Chris Avatar asked Jun 17 '13 18:06

Chris


2 Answers

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?

like image 57
falsetru Avatar answered Nov 18 '22 11:11

falsetru


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
like image 43
Matt Good Avatar answered Nov 18 '22 11:11

Matt Good