用Flas正确重载json编解码

2024-04-26 00:47:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在flaskjson编码器/解码器中添加一些重载来添加datetime编码/解码,但只通过“hack”成功了。在

from flask import Flask, flash, url_for, redirect, render_template_string
from flask.json import JSONEncoder, JSONDecoder


template = """
<!DOCTYPE html>
<html><head><title>Test JSON encoder/decoder</title></head><body>
{% with messages = get_flashed_messages(with_categories=true) %}{% if messages %}{% for message in messages %}
<p>Flash: {{ message }}</p>
{% endfor %}{% endif %}{% endwith %}
<p>Flash should be: ['Flash message', 'success']</p>
<p><a href="{{ url_for('index') }}">Try again</a></p>
</body></html>
"""


class CustomJSONEncoder(JSONEncoder):
    """ Do nothing custom json encoder """
    def default(self, obj):
        # My custom logic here
        # ...
        # or
        return super(CustomJSONEncoder, self).defaults(obj)


class CustomJSONDecoder(JSONDecoder):
    """ Do nothing custom json decoder """
    def __init__(self, *args, **kargs):
        _ = kargs.pop('object_hook', None)
        super(CustomJSONDecoder, self).__init__(object_hook=self.decoder, *args, **kargs)

    def decoder(self, d):
        # My custom logic here
        # ...
        # or
        return d


app = Flask(__name__, static_url_path='')
app.config['SECRET_KEY'] = 'secret-key'
app.json_encoder = CustomJSONEncoder
app.json_decoder = CustomJSONDecoder


@app.route('/')
def index():
    flash('Flash message', 'success')
    return redirect(url_for('display'))


@app.route('/b')
def display():
    return render_template_string(template)


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

问题是我应该从Flask.sessions.TaggedJSONSerializer像这样:

^{pr2}$

我是“正确地”做的还是我错过了什么?在


Tags: selfjsonappurlflaskmessageforreturn
2条回答

通过显式调用基类的default()方法,可以使用基类的功能。我已经在我的自定义JSONEncoder中成功地做到了:

class CustomJSONEncoder(JSONEncoder):
    def default(self, obj):
        # Calling custom encode function:
        jsonString = HelperFunctions.jsonEncodeHandler(obj)
        if (jsonString != obj):  # Encode function has done something
            return jsonString  # Return that
        return JSONEncoder.default(self, obj)  # else let the base class do the work

但是,在解码器中,您应该记住传递给__init__()函数的对象钩子,并从您自己的钩子调用它:

^{pr2}$

顺便说一句:您的解码器中有一个输入错误:您在基类中注册的对象钩子名为self.decoder,但成员被定义为def decode(...)(末尾没有r)。在您的例子中,您注册了一个空钩子,decode()永远不会被调用。在

请注意,您必须告诉烧瓶应用程序它将使用什么编码器:

app.json_encoder = CustomJSONEncoder

这解决了我的问题。在

相关问题 更多 >