我应该对pickle进行base64编码以通过网络发送/存储到数据库中吗?

发布于 2025-01-11 07:28:58 字数 106 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

安静被遗忘 2025-01-18 07:28:58

JSON 表示形式是字符串。但即使我的 JSON 序列化字符串包含不在可打印 ASCII 字符集范围内的 Unicode 字符,Python 也会默认选择在 ASCII 可打印范围内的这些字符的表示形式 (ensure_ascii=True 是 json.dumps 调用的默认值)。例如:

print(json.dumps('圣诞节\n\000'));

打印:

"\u5723\u8bde\u8282\n\u0000"

上述序列化表示中没有任何内容需要特殊编码。现在的问题是您希望序列化的对象是否需要特殊编码。例如,如果对象具有 decimal.Decimal 类型的属性,该属性不是受支持的 JSON 可序列化类型之一,则您需要存储该属性的字符串表示形式。

例如:

from decimal import Decimal
import json

class MyClass:
    def __init__(self, a: int, b: Decimal):
        self.a = a
        self.b = b

    def __repr__(self):
        return f'a = {self.a}, b = {self.b}'

    def serialize(self):
        return json.dumps({'a': self.a, 'b': str(self.b)})

    @classmethod
    def deserialize(cls, s):
        state = json.loads(s)
        return cls(state['a'], Decimal(state['b']))

obj1 = MyClass(3, Decimal('7.93'))
print('obj1:', obj1)
saved_state = obj1.serialize()
print('Saved state:', saved_state)
obj2 = MyClass.deserialize(saved_state)
print('obj2:', obj2)

打印:

obj1: a = 3, b = 7.93
Saved state: {"a": 3, "b": "7.93"}
obj2: a = 3, b = 7.93

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:

print(json.dumps('圣诞节\n\000'));

Prints:

"\u5723\u8bde\u8282\n\u0000"

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:

from decimal import Decimal
import json

class MyClass:
    def __init__(self, a: int, b: Decimal):
        self.a = a
        self.b = b

    def __repr__(self):
        return f'a = {self.a}, b = {self.b}'

    def serialize(self):
        return json.dumps({'a': self.a, 'b': str(self.b)})

    @classmethod
    def deserialize(cls, s):
        state = json.loads(s)
        return cls(state['a'], Decimal(state['b']))

obj1 = MyClass(3, Decimal('7.93'))
print('obj1:', obj1)
saved_state = obj1.serialize()
print('Saved state:', saved_state)
obj2 = MyClass.deserialize(saved_state)
print('obj2:', obj2)

Prints:

obj1: a = 3, b = 7.93
Saved state: {"a": 3, "b": "7.93"}
obj2: a = 3, b = 7.93

Note

If you named your methods __getstate__ (instead of serialize) and __setstate__ (instead of deserialize) and made the latter a regular instance method rather than a class method, then the class would also be compatible with the pickle 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文