TypeError:Flask app

时间:2016-10-04 17:14:59

标签: python json flask

我正在尝试实现一个简单的烧瓶应用程序,它将json文件传递到前端,但出现如下错误:

> 127.0.0.1 - - [04/Oct/2016 17:53:02] "GET /test HTTP/1.1" 500 - Traceback (most recent call last):   File
> "/Users/michelleshieh/anaconda2/lib/python2.7/site-packages/flask/app.py",
> line 2000, in __call__
>     return self.wsgi_app(environ, start_response)   File "/Users/michelleshieh/anaconda2/lib/python2.7/site-packages/flask/app.py",
> line 1992, in wsgi_app
>     return response(environ, start_response)   File "/Users/michelleshieh/anaconda2/lib/python2.7/site-packages/werkzeug/wrappers.py",
> line 1228, in __call__
>     app_iter, status, headers = self.get_wsgi_response(environ)   File "/Users/michelleshieh/anaconda2/lib/python2.7/site-packages/werkzeug/wrappers.py",
> line 1216, in get_wsgi_response
>     headers = self.get_wsgi_headers(environ)   File "/Users/michelleshieh/anaconda2/lib/python2.7/site-packages/werkzeug/wrappers.py",
> line 1167, in get_wsgi_headers
>     for x in self.response)   File "/Users/michelleshieh/anaconda2/lib/python2.7/site-packages/werkzeug/wrappers.py",
> line 1167, in <genexpr>
>     for x in self.response)   File "/Users/michelleshieh/anaconda2/lib/python2.7/site-packages/werkzeug/_compat.py",
> line 112, in to_bytes
>     raise TypeError('Expected bytes') TypeError: Expected bytes
> 127.0.0.1 - - [04/Oct/2016 17:53:03] "GET /favicon.ico HTTP/1.1" 404

与网址相关的编码&#39; / test&#39;是:

@app.route("/test",methods=['GET'])

    def get_local_json():
        SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
        json_url = os.path.join(SITE_ROOT, "static/data","predict.json")
        #console.log("url is all right")
        data = json.load(open(json_url))
        return app.response_class(data, content_type='application/json')

前端的相应代码:

$.getJSON('/test', function(data){  
        var myData = [];
        for(var i in data){
            var item = data[i];
            var myItem = [];
            myItem.push(new Date(item.time).getTime());
            myItem.push(item.occupancy);
            myData.push(myItem);
        }
        console.log(myData);

任何提示都表示赞赏!!

1 个答案:

答案 0 :(得分:2)

您将在此处返回除bytes对象以外的Python对象:

return app.response_class(data, content_type='application/json')

这不是JSON响应,而是未编码的 Python列表或字典。

只需返回JSON数据,不用解码它:

    with open(json_url, 'rb') as json_file:
        return app.response_class(json_file.read(), content_type='application/json')

或者如果您必须先对数据结构执行某些操作,请将其重新编码回JSON。使用jsonify()实用程序功能:

with open(json_url) as json_file:
    data = json.load(json_file)

# manipulate data as needed

return jsonify(data)