Python 使用Flask正确重载json编码和解码
我试图向Flask JSON编码器/解码器添加一些重载,以添加日期时间编码/解码,但仅通过“黑客”成功Python 使用Flask正确重载json编码和解码,python,json,session,flask,decoding,Python,Json,Session,Flask,Decoding,我试图向Flask JSON编码器/解码器添加一些重载,以添加日期时间编码/解码,但仅通过“黑客”成功 from flask import Flask, flash, url_for, redirect, render_template_string from flask.json import JSONEncoder, JSONDecoder template = """ <!DOCTYPE html> <html><head><title>
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)
我做得是否“正确”,或者我遗漏了什么?可以通过显式调用基类的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
但是,在解码器中,您应该记住传递给\uuuu init\uuu()函数的对象钩子,并从您自己的钩子调用它:
class CustomJSONDecoder(JSONDecoder):
def __init__(self, *args, **kwargs):
self.orig_obj_hook = kwargs.pop("object_hook", None)
super(CustomJSONDecoder, self).__init__(*args,
object_hook=self.custom_obj_hook, **kwargs)
def custom_obj_hook(self, dct):
# Calling custom decode function:
dct = HelperFunctions.jsonDecodeHandler(dct)
if (self.orig_obj_hook): # Do we have another hook to call?
return self.orig_obj_hook(dct) # Yes: then do it
return dct # No: just return the decoded dict
顺便说一句:您的解码器中有一个输入错误:您在基类中注册的对象挂钩名为self.decoder
,但成员定义为def decode(…)
(末尾没有r)。在您的示例中,您注册了一个空钩子,并且不应该调用decode()
。注意,您必须告诉您的flask应用程序它将使用什么编码器:
app.json_encoder = CustomJSONEncoder
这解决了我的问题
app.json_encoder = CustomJSONEncoder