文章目录
  1. 1. 前言
  2. 2. 使用
    1. 2.1. JSON 缩进
    2. 2.2. Unicode 编码
  3. 3. 参考资料
  4. 4. 文档信息

前言


记录使用 Flask-RESTful 过程中的小问题和小技巧

使用


每种场景都有对应的方法。

JSON 缩进


在请求的 API 接口中,JOSN 数据展示这种类似结构:

1
2
3
4
5
6
7
8
{
"code": 200,
"ad": {
"title": "抗病毒除菌杀菌喷雾除臭喷雾去味活性银离子杀菌消毒除臭剂居家旅行伴侣正常发货 100ml家庭装",
"url": "https://u.jd.com/bY0BlR",
"price": "拼购价:¥29.90"
}
}

If the application is running in debug mode (app.debug = True) and either sort_keys or indent are not declared in the RESTFUL_JSON configuration setting, Flask-RESTful will provide defaults of True and 4 respectively.

1
2
3
4
class MyConfig(object):
RESTFUL_JSON = {'indent': 4,
'sort_keys': False,
'separators': (', ', ': ')}

上面单个配置:

1
2
3
app = Flask(__name__)
app.config.from_object(MyConfig) #加载配置
api = Api(app)

Unicode 编码


JSON_AS_ASCII
Serialize objects to ASCII-encoded JSON. If this is disabled, the JSON will be returned as a Unicode string, or encoded as UTF-8 by jsonify. This has security implications when rendering the JSON into JavaScript in templates, and should typically remain enabled.

JSON_AS_ASCII

将对象序列化为 ASCII 编码的 JSON,如果被禁用,JSON 将以 Unicode 字符串形式返回,或由 jsonify 编码为 UTF-8。将 JSON 渲染到模板 JavaScript 中时具有安全性,所以应该保持启用状态。

ensure_ascii 设置为 False,非 ASCII 编码不要转义。

1
2
3
4
5
6
7
8
class MyConfig(object):
# 'ensure_ascii': False, non-ASCII 非 ascii 不要转义,返回 Unicode 字符串
# 'indent': 4 缩进
RESTFUL_JSON = {'indent': 4,
'sort_keys': False,
'ensure_ascii': False,
'separators': (', ', ': '),
}

参考资料


文档信息


  • 版权声明:自由转载-保持署名-非商用-非衍生 ( CC BY-NC-ND 4.0 )
文章目录
  1. 1. 前言
  2. 2. 使用
    1. 2.1. JSON 缩进
    2. 2.2. Unicode 编码
  3. 3. 参考资料
  4. 4. 文档信息