我应该对pickle进行base64编码以通过网络发送/存储到数据库中吗?
Pickle 是一种序列化 python 对象的方法。
假设我想通过网络发送它或存储在数据库中,那么我可以(分别)发送/存储pickle值还是需要对pickle值进行base64编码?
Pickle is a way to serialize the python object.
Suppose I want to send this over the network or store in a database, then can I send/store (respectively) the pickle value or do I need to base64 encode the pickle value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JSON 表示形式是字符串。但即使我的 JSON 序列化字符串包含不在可打印 ASCII 字符集范围内的 Unicode 字符,Python 也会默认选择在 ASCII 可打印范围内的这些字符的表示形式 (ensure_ascii=True 是 json.dumps 调用的默认值)。例如:
打印:
上述序列化表示中没有任何内容需要特殊编码。现在的问题是您希望序列化的对象是否需要特殊编码。例如,如果对象具有
decimal.Decimal
类型的属性,该属性不是受支持的 JSON 可序列化类型之一,则您需要存储该属性的字符串表示形式。例如:
打印:
Note
如果您将方法命名为
__getstate__
(而不是serialize
)和__setstate__
(而不是deserialize
) 并使后者成为常规实例方法而不是类方法,那么该类也将与pickle
模块兼容,尽管您需要考虑是否您想要使用标准当您不需要通过网络发送对象或将其保存在数据库中或不需要数据表示稳定性时,使用酸洗方法。JSON representations are strings. But even when I have JSON-serialized strings that contain Unicode characters that are not in the printable ASCII character set range, Python chooses a representation of these characters that are in the ASCII-printable range by default (ensure_ascii=True is the default value for the
json.dumps
call). For example:Prints:
There is nothing in the above serialized representation that requires special encoding. Now the issue is whether the object that you wish to serialize requires special encoding. For example, if the object has an attribute that is of type
decimal.Decimal
, which is not one of the supported JSON-serializable types, you would want to store the the string representation of this attribute.For example:
Prints:
Note
If you named your methods
__getstate__
(instead ofserialize
) and__setstate__
(instead ofdeserialize
) and made the latter a regular instance method rather than a class method, then the class would also be compatible with thepickle
module, though you need to think about whether you would want to use the standard pickling methodology for when you do not need to send the object across the wire or have it saved in a database or don't need the data-representation stability.