类型错误:Flask 应用程序中的预期字节数

Mic*_*ieh 3 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
Run Code Online (Sandbox Code Playgroud)

与 url '/test' 相关的编码是:

@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')
Run Code Online (Sandbox Code Playgroud)

以及前端的对应代码:

$.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);
Run Code Online (Sandbox Code Playgroud)

任何提示表示赞赏!

Mar*_*ers 5

您正在返回一个 Python 对象而不是bytes这里的对象:

return app.response_class(data, content_type='application/json')
Run Code Online (Sandbox Code Playgroud)

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

只需返回 JSON 数据而不对其进行解码:

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

或者,如果您必须先对数据结构进行处理,请将其重新编码回 JSON。jsonify()为此使用效用函数:

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

# manipulate data as needed

return jsonify(data)
Run Code Online (Sandbox Code Playgroud)