当使用Apache/uWSGI或Werkzeug时,flask json输出看起来有所不同



Json输出在使用Apache/uWSGI和Werkzeug时看起来有所不同。诀窍在哪里?

参见示例:

Werkzeug:

curl -k -iL http://127.0.0.1:5000/test/
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 32
Content-Type: application/json
Server: Werkzeug/0.14.1 Python/3.6.6
Date: Tue, 30 Oct 2018 18:13:37 GMT
{
"data": "Hello, Api!"
}

Apache/uWSGI提供的相同代码:

curl -k  -iL https://flask.xxxxx.local/test/
HTTP/1.1 200 OK
Date: Tue, 30 Oct 2018 18:13:39 GMT
Server: Apache
Content-Type: application/json
Content-Length: 27
{"data":"Hello, Api!"}

我在等:

{
"data": "Hello, Api!"
}

这段代码:

from flask import Flask, jsonify, abort, make_response, render_template, g
from flask_restful import Api, Resource, reqparse, fields, marshal
...
@app.route('/test/')
def get_resource():
headers = {'Content-Type': 'application/json'}
content = { 'data': 'Hello, Api'}
return make_response(jsonify(content),200,headers)
...
Flask==1.0.2
Flask-RESTful==0.3.6
uWSGI==2.0.17.1
Werkzeug==0.14.1

thx

差异的原因是烧瓶配置设置JSONIFY_PRETTYPRINT_REGULAR

此设置具有默认值False,但在调试模式下运行时始终为True

因此,当您在uSgi/Apache下运行时,将使用False的默认设置,不提供缩进/换行。当您在Werkzeug测试服务器上以调试模式运行时,Flask会将值设置为True

要在uwsgi下获得缩进和换行,请在wsgi脚本中执行以下操作:

app = Flask(...)
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True

请参阅文档:http://flask.pocoo.org/docs/1.0/config/#JSONIFY_PRETTYPRINT_REGULAR

此外,您不需要make_response()调用。你可以简单地做:

@app.route('/test/')
def get_resource():
content = { 'data': 'Hello, Api'}
return jsonify(content)

并且Flask将设置正确的内容类型。

最新更新