python – Flask:’Response’对象不能与响应生成异常一起迭代

前端之家收集整理的这篇文章主要介绍了python – Flask:’Response’对象不能与响应生成异常一起迭代前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我似乎无法在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",in _iter_encoded
    for item in iterable:
TypeError: 'Response' object is not iterable

回溯是意外的.

解决方法

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,'application/json')]
原文链接:https://www.f2er.com/python/186694.html

猜你在找的Python相关文章