python - 当使用 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
谢谢
解决方案
差异的原因是 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 将设置正确的内容类型。
推荐阅读
- python - 无法弄清楚如何在张量中使用值
- vue.js - Quasar Framework (Vue) Uploader 使用 apollo-upload (GraphQL)
- python-3.x - 在自己的图像上测试网络
- php - 在 Laravel 5.7 中合并具有多个键的集合
- typescript - 如何为客户端转译打字稿
- c# - 第一次调用异步等待仍然有错误 IEnumerable
不包含 GetAwaiter 的定义 - algorithm - 如何为多人游戏随机创建一个公平的迷宫?
- php - 如何使用多个标签快速搜索帖子/列表?
- c# - 将网络开始位置添加到游戏对象后如何修复触发器
- indexing - Dspace 作者索引不敏感的口音