当使用 Apache/uWSGI 和 Werkzeug 时,Json 输出看起来会有所不同。 窍门在哪里?
参见示例:
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
谢谢
最佳答案
造成差异的原因是 Flask 配置设置 JSONIFY_PRETTYPRINT_REGULAR
此设置具有默认值 False
,但在 Debug模式下运行时始终为 True
。
因此,当您在 uWsgi/Apache 下运行时,将使用默认设置 False,不提供缩进/换行符。当您在 Werkzeug 测试服务器上以 Debug模式运行时,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 将设置正确的内容类型。
关于python - 当使用 Apache/uWSGI 或 Werkzeug 时,flask json 输出看起来有所不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53071282/