[英]How to exclude specific fields on serialization with jsonpickle?
I'm using SQLAlchemy extension with Flask. 我正在使用Flask的SQLAlchemy扩展。 While serializing my models (which are also used for database operations) using jsonpickle, I want some specific attributes to be ignored. 在使用jsonpickle序列化我的模型(也用于数据库操作)时 ,我想要忽略一些特定的属性。 Is there a way that allows me to set those rules? 有没有办法让我设定这些规则?
SQLAlchemy adds an attribute named _sa_instance_state
to the object. SQLAlchemy将一个名为_sa_instance_state
的属性添加到对象中。 In a word, I do not want this field to be in the JSON output. 总之,我不希望这个字段在JSON输出中。
You cannot tell the default class pickler to ignore something, no. 您不能告诉默认的类选择器忽略某些东西,不。
jsonpickle
does support the pickle
module __getstate__
and __setstate__
methods. jsonpickle
确实支持pickle
模块 __getstate__
和__setstate__
方法。 If your classes implement those two methods, whatever is returned is then used by jsonpickle
to represent the state instead. 如果您的类实现了这两个方法,那么jsonpickle
将使用返回的jsonpickle
来代表状态。 Both methods do need to be implemented. 这两种方法都需要实施。
If __getstate__
is not implemented, jsonpickle
uses the __dict__
attribute instead, so your own version merely needs to use that same dictionary, remove the _sa_instance_state
key and you are done: 如果__getstate__
不落实, jsonpickle
使用__dict__
属性,而不是,所以你自己的版本只需要使用相同的字典,取出_sa_instance_state
键和你做:
def __getstate__(self):
state = self.__dict__.copy()
del state['_sa_instance_state']
return state
def __setstate__(self, state):
self.__dict__.update(state)
Whatever __getstate__
returns will be processed further, recursively, there is no need to worry about handling subobjects there. 无论__getstate__
返回什么__getstate__
将以递归方式进一步处理,因此无需担心在那里处理子对象。
If adding __getstate__
and __setstate__
is not an option, you can also register a custom serialization handler for your class; 如果添加__getstate__
和__setstate__
不是一个选项,您还可以为您的类注册自定义序列化处理程序 ; the disadvantage is that while __getstate__
can get away with just returning a dictionary, a custom handler will need to return a fully flattened value. 缺点是虽然__getstate__
只能返回一个字典,但自定义处理程序需要返回一个完全展平的值。
This one will help others to get their task done: 这个将帮助其他人完成他们的任务:
Make a class like this one in a package like your custom jsonpickle
package: 像你的自定义jsonpickle
包一样在类包中创建一个这样的类:
class SetGetState:
def __getstate__(self):
state = self.__dict__.copy()
try:
class_name = '_' + self.__class__.__name__ + '__'
new_items = {key:value for key, value in state.items() if class_name not in key}
return new_items
except KeyError:
pass
return state
And inherit this one in the class requires no private property serialization 并且在类中继承这个不需要私有属性序列化
class Availability(jsonpickle.SetGetState):
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.