Flask JSONEncoder将ensure_ascii设置为False [英] Flask JSONEncoder set ensure_ascii to False

查看:1071
本文介绍了Flask JSONEncoder将ensure_ascii设置为False的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个小瓶子应用程序中,我想要返回包含变音符的字符串(通常是德语特殊字符,例如ß)。由于烧瓶中的$ code> JSONEncoder 的默认值为$ code> ensure_ascii = True ,这将永远转换我的字符串

I'm working on a small flask app in which I want to return strings containing umlauts (in general German special characters, e.g 'ß'). As the default JSONEncoder in flask has ensure_ascii=True, this will always convert my string

Hauptstraße 213

Hauptstra\u00dfe 213

我的第一种方法是创建一个非常基本的自定义 JSONEncoder

My first approach was to just create a very basic custom JSONEncoder

class NonAsciiJSONEncoder(json.JSONEncoder):
    def __init__(self, **kwargs):
        super(NonAsciiJSONEncoder, self).__init__(kwargs)
        self.ensure_ascii = False 

如果我使用这个,通过设置

If I use this, by setting

app.json_encoder = NonAsciiJSONEncoder

我的 return jsonify(...)将实际返回包含'ß'的字符串。

my return jsonify(...) will actually return the string containing 'ß'.

但是,由于 ensure_ascii 是默认编码器的属性,我认为只是更改它可能会更好通过将它设置为 False

However, as ensure_ascii is an attribute of the default Encoder, I thought it might be better to just change it by setting it to False

app.json_encoder.ensure_ascii = False

这将在返回之前将属性设置为False。但是不知何故,字符串仍然没有ß但是 \\\ß 返回。

This will actually set the property to False which I checked before returning. But somehow, the string is still returned without 'ß' but with \u00df.

正如我在自定义编码器中所做的一样,将这个属性设置为 False

How can this be, as all I'm doing in my custom Encoder, is setting this attribute to False?

推荐答案

更改 app.json_encoder时,您正在设置一个属性。

JSONEncoder .__ init __ 方法将实例属性设置为 True ,因为 ensure_ascii 参数的默认值。设置类属性不会阻止 __ init __ 方法设置实例属性,它是在这里获得的实例属性。

The JSONEncoder.__init__ method sets an instance attribute to True, as that is the default value for the ensure_ascii argument. Setting the class attribute won't prevent the __init__ method from setting an instance attribute, and it is the instance attribute that wins here.

您可以让您的子类设置参数为 False

You could just have your subclass set the argument to False:

class NonASCIIJSONEncoder(json.JSONEncoder):
    def __init__(self, **kwargs):
        kwargs['ensure_ascii'] = False
        super(NonASCIIJSONEncoder, self).__init__(**kwargs)

这篇关于Flask JSONEncoder将ensure_ascii设置为False的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆