Flag error handling: "The response object is not iterable"

I am trying to install a REST web service using Flask. I had a problem with 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 do this, I get nothing. In my debugger, this tells me that I have a TypeError: 'Response' object is not iterable

I used jsonify in another method with a dictionary without problems, but when I return it as an error, it does not work. Any ideas?

+6
source share
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 the curl http://localhost:5000/ code above, curl http://localhost:5000/ give me:

 { "error": "not found" } 

Are you flask.jsonify ?

+8
source

As mentioned in the comments to the previous answer, this code is not supported on Flask 0.8 and requires 0.9 or higher. If you need to support Flask 0.8, here is a compatible version that assigns "status_code" instead:

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

Source: https://habr.com/ru/post/947492/


All Articles