Flask JSONEncoder set ensure_ascii to False

2019-06-22 08:43发布

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

to this:

Hauptstra\u00dfe 213

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

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

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

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

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

1条回答
一夜七次
2楼-- · 2019-06-22 09:22

You are setting a class attribute when altering app.json_encoder.ensure_ascii, which is not the same thing as an instance attribute.

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.

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)
查看更多
登录 后发表回答