修复类以启用Flask会话中的对象存储 [英] Fixing the class to enable object storing in Flask session
问题描述
我有一个自定义的Passport类,它包含活动的用户标识和权限。我曾经像这样在会话中存储它:
$ b $ pre $ passport()
p.do_something_fancy()
session [passport] = p
现在,服务器升级后,我收到了这个错误:
TypeError:< userman.Passport instance at 0x7f06e9356f38>是不是JSON可序列化
我猜这是连接到Flask中的一些升级现在需要的对象JSON序列化以存储在会话中。但是,如何正确地使一个对象JSON序列化?也许我必须提供一个序列化的方法,还有一个反序列化的方法,当它再次被加载的时候恢复对象的状态?
<你必须创建一个自定义的 JSONEncoder
类,并告诉Flask使用这个JSON序列化/反序列化。
下面是它的工作方式: I have a custom class Passport that contains the active user identity and permissions. I used to store it in session just like this: and it just worked. Now, after server upgrade, I am receiving this error: I guess it is connected to some upgrades in Flask that now require the object to be JSON-serializable to be stored in session. But how do I properly make an object JSON-serializable? Perhaps I have to provide a method for serialization and also a method for deserialization, to restore the object state when it's being loaded again? You have to create a custom Here is how it would roughly work:
这篇关于修复类以启用Flask会话中的对象存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ b $ p $ from flask.json import JSONEncoder
$ b $ class CustomJSONEncoder(JSONEncoder ):
def default(self,obj):
如果是isinstance(obj,Passport):
#将Passport对象转换为字典
返回passport_dict
else:
现在告诉Flask使用自定义类
app.json_encoder = CustomJSONEncoder
$ / code > p = Passport()
p.do_something_fancy()
session["passport"] = p
TypeError: <userman.Passport instance at 0x7f06e9356f38> is not JSON serializable
JSONEncoder
class and tell Flask to use this for JSON serialization/deserialization.from flask.json import JSONEncoder
class CustomJSONEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, Passport):
# Implement code to convert Passport object to a dict
return passport_dict
else:
JSONEncoder.default(self, obj)
# Now tell Flask to use the custom class
app.json_encoder = CustomJSONEncoder