烧瓶 - 宁静需要jsonify否则它不起作用

时间:2017-04-15 20:10:10

标签: python json rest api

我正在使用Flask和Flask-RESTful制作API。当我在浏览器中访问URL以发出HTTP GET请求时,我在chrome开发者控制台中收到了一个奇怪的警告:

Resource interpreted as Document but transferred with MIME type application/json: "http://localhost:8080/api/articles".

所以我查了一下,this文章建议我将mime类型更改为text/html,但这并不起作用。

此外,当我用我的前端角度测试时,没有自动将它变成json,它通常会做什么。

那么为什么会这样呢? 我注意到一件奇怪的事。 jsonify的普通视图返回与flask restfull资源相同的功能。所以我想我尝试将jsonify添加到返回中并且它可以正常工作。

我的问题是为什么这只能在我使用jsonify函数时才起作用,否则不起作用。在Flask-RESTful的文档中,它表示它不需要jsonify函数。因为@api.representation('application/json')使用json.dumps并在每个传出响应中添加了mime类型。

class ArticleList(Resource):
    def get(self):
        results = models.Article.query.all()
        return [x.as_dict() for x in results]  # doesn't work
        # return jsonify([x.as_dict() for x in results]) this does work

我还使用jsonify和没有。{/ p>进行了curl请求

使用jsonify

panter@panter:~$ curl -X GET http://localhost:8080/api/articles -v
Note: Unnecessary use of -X or --request, GET is already inferred.
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /api/articles HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.47.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Type: application/json
< Content-Length: 560
< Date: Sat, 15 Apr 2017 19:46:46 GMT
< 
[
  {
    "body": "boeeeeeem", 
    "id": 1, 
    "picture": null, 
    "timestamp": "za, 15 apr 2017 17:56:48", 
    "title": "Vandaag in nuenen een grote explosie!"
  }
]

没有jsonify

panter@panter:~$ curl -X GET http://localhost:8080/api/articles -v
Note: Unnecessary use of -X or --request, GET is already inferred.
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /api/articles HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.47.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Type: application/json
< Content-Length: 466
< Date: Sat, 15 Apr 2017 19:43:20 GMT
< 
[{"body": "boeeeeeem", "picture": null, "id": 1, "timestamp": "za, 15 apr 2017 17:56:48", "title": "Vandaag in nuenen een grote explosie!"}]

另请注意,我已更改@api.representation('application/json')以添加一些自定义标头:

@api.representation('application/json')
def output_json(data, code, headers=None):
    resp = make_response(json.dumps(data), code)
    all_headers = {
        'Access-Control-Allow-Headers': 'Content-Type, Authorization',
        'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT, PATCH, DELETE',
        'Access-Control-Allow-Origin': '*'
    }.copy()
    all_headers.update(headers)
    resp.headers.extend(all_headers)

    return resp

使用jsonify时,不会使用这些自定义标题。

0 个答案:

没有答案
相关问题