我似乎无法在Flask 0.10.1中生成异常响应(0.9也是如此)。这段代码:
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
打印
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
追溯是意外的。
答案 0 :(得分:16)
jsonify()
生成完整回复对象,而不是回复正文,因此请使用HTTPException.get_response()
,而不是.get_body()
:
class JSONException(HTTPException):
def get_response(self, environ):
return jsonify(a=1)
另一种方法是在这里使用json.dumps()
生成一个主体:
class JSONException(HTTPException):
def get_body(self, environ):
return json.dumps({a: 1})
def get_headers(self, environ):
return [('Content-Type', 'application/json')]