将 Python 对象序列化为纯文本字符串

评论 0 浏览 0 2020-11-09

什么是序列化?

序列化是将对象转换为字节流的过程,以便将对象存储或传输到内存、数据库或文件中。其主要目的是保存对象的状态,以便在需要时重新创建。反向过程称为反序列化。
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/

使用Pickle

Pickle 是一个 Python 标准库,允许将任何 Python 对象序列化为二进制字符串或二进制文件。它还允许从序列化数据重新创建新对象。

以下代码片段演示了如何将某个对象序列化为二进制字符串并将其反序列化为另一个对象

import pickle

# Some class for demonstration
class Demo:
    def __init__(self):
        # It has some data which can be serialized
        self.some_data = "hello"

    def say_hello(self):
        print(self.some_data)

# Creating an instance of Demo class
obj = Demo()

# Serializing the object into a binary string
obj_string = pickle.dumps(obj)

# De-serializing into another object
obj2 = pickle.loads(obj_string)

# Checking the the new object is working
# It should print: Hello
obj2.say_hello()

以下代码片段演示了如何将某个对象序列化为二进制文件并将其反序列化为另一个对象:

import pickle

# Some class for demonstration
class Demo:
    def __init__(self):
        # It has some data which can be serialized
        self.some_data = "hello"

    def say_hello(self):
        print(self.some_data)

# Creating an instance of Demo class
obj = Demo()

# Serializing the object into a binary file 'obj_file.bin'
pickle.dump(obj, open('obj_file.bin', 'wb'))

# Reading the binary file
# and de-serializing into another object
obj2 = pickle.load(open('obj_file.bin', 'rb'))

# Checking the the new object is working
# It should print: Hello
obj2.say_hello()

转换为纯文本

Pickle 将对象序列化为二进制字符串或文件,但有时我们需要使用纯文本格式,例如当我们想要通过仅允许使用纯文本的通信通道传输某个对象的状态时。

可以将二进制字符串转换为纯文本字符串的 Base64 字符串。

以下代码片段演示了如何将某个对象序列化为纯文本字符串并将其反序列化为另一个对象:

import pickle
import base64

# Serialize an object into a plain text
def obj_to_txt(obj):
    message_bytes = pickle.dumps(obj)
    base64_bytes = base64.b64encode(message_bytes)
    txt = base64_bytes.decode('ascii')
    return txt

# De-serialize an object from a plain text
def txt_to_obj(txt):
    base64_bytes = txt.encode('ascii')
    message_bytes = base64.b64decode(base64_bytes)
    obj = pickle.loads(message_bytes)
    return obj

# Some class for demonstration
class Demo:
    def __init__(self):
        # It has some data which can be serialized
        self.some_data = "hello"

    def say_hello(self):
        print(self.some_data)

# Creating an instance of Demo class
obj = Demo()

# Serializing the object into a plain text
obj_string = obj_to_txt(obj)

# De-serializing the plain text into another object
obj2 = txt_to_obj(obj_string)

# Checking the the new object is working
# It should print: Hello
obj2.say_hello()

最初发布于https:// www.orensifri.meddevsoft.com

最后更新2024-09-17
0 个评论
标签