【问题标题】:My flask app doesn't return non-ascii character properly我的烧瓶应用程序没有正确返回非 ascii 字符
【发布时间】:2019-04-29 12:39:26
【问题描述】:

我正在尝试使用 flask-restful api,作为返回值,代码应该返回一个 json 数据列表。但是,当 json 中的内容是非 ascii 字符时,如 (èòsèèò) 返回值

这是一个示例代码:

#! /usr/bin/env python
# coding: utf-8

from flask import Flask, Response
from flask_restful import Resource, Api
import json

app = Flask(__name__)
# Create the API
API = Api(app)



@app.route('/')
def hello_world():
    return Response('Here, with Response it works well: höne')

class APICLASS(Resource):
    """

    """
    def get(self, id):
        return [
        {
        "hey": 11,
        "test": "höne"
        }], 200


API.add_resource(APICLASS, '/<string:id>')

if __name__ == '__main__':
    app.run(debug=True)

但是当我在 localhost 上检查结果时,我看到以下输出:

[
        {
        "hey": 11,
        "test": "h\u00f6ne"
        }]

【问题讨论】:

  • 说实话我没看懂你的问题!我正在从数据库中检索所有数据作为 Json 的列表。但是在传递给 flask restful Api 之前就可以了。即使,如果我传递像 "höne" 这样的单个字符串而不是 json 列表,我仍然会看到问题
  • 我不知道它怎么不能正确传输。当我尝试使用上面的代码直接返回一个没有任何列表的非 ascii 字符时,我得到了同样的错误!

标签: python utf-8 python-3.7 non-ascii-characters flask-restful


【解决方案1】:

显然与this bug有关。 我不确定是否有任何副作用,但这可能会有所帮助:

# ...
app = Flask(__name__)
# Create the API
API = Api(app)

API.app.config['RESTFUL_JSON'] = {
    'ensure_ascii': False
}

@app.route('/')
# Rest of your code

【讨论】:

  • 谢谢它的工作。它只需添加代码的最后一部分即可:api.app.config['RESTFUL_JSON'] = { 'ensure_ascii': False}
  • 您能否告诉我如何将您的代码添加为一个类,并在其他类中调用它?如您提供的链接中所示
猜你喜欢
  • 2018-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-23
  • 1970-01-01
  • 2020-05-09
相关资源
最近更新 更多