How to deserialize an object with PyYAML using safe_load?

前端 未结 3 669
攒了一身酷
攒了一身酷 2021-02-15 15:20

Having a snippet like this:

import yaml
class User(object):
    def __init__(self, name, surname):
       self.name= name
       self.surname= surname

user = U         


        
3条回答
  •  别跟我提以往
    2021-02-15 15:50

    It appears that safe_load, by definition, does not let you deserialize your own classes. If you want it to be safe, I'd do something like this:

    import yaml
    class User(object):
        def __init__(self, name, surname):
           self.name= name
           self.surname= surname
    
        def yaml(self):
           return yaml.dump(self.__dict__)
    
        @staticmethod
        def load(data):
           values = yaml.safe_load(data)
           return User(values["name"], values["surname"])
    
    user = User('spam', 'eggs')
    serialized_user = user.yaml()
    print "serialized_user:  %s" % serialized_user.strip()
    
    #Network
    deserialized_user = User.load(serialized_user)
    print "name: %s, sname: %s" % (deserialized_user.name, deserialized_user.surname)
    

    The advantage here is that you have absolute control over how your class is (de)serialized. That means that you won't get random executable code over the network and run it. The disadvantage is that you have absolute control over how your class is (de)serialized. That means you have to do a lot more work. ;-)

提交回复
热议问题