首页 > 解决方案 > 当使用 Apache/uWSGI 或 Werkzeug 时,flask json 输出看起来会有所不同

问题描述

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

见例子:

韦克泽格:

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

谢谢

标签: pythonapacheflaskuwsgiflask-restful

解决方案


差异的原因是 Flask 配置设置JSONIFY_PRETTYPRINT_REGULAR

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

因此,当您在 uWsgi/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 将设置正确的内容类型。


推荐阅读