1

我正在尝试开发我的非 ORM 类的 ORM 版本,以便能够将对象存储在数据库中(并在可能的情况下将其取回)。

from ruamel.yaml import YAMLObject

class User(YAMLObject):
    yaml_tag = u'user'

    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Other useful methods

我现在想要实现的是一个类似的对象,它的行为类似于UserPython 世界,但它也可以用作 ORM 对象,因此能够将它存储在数据库中。我巧妙地尝试的是:

Base = declarative_base()

class SQLUser(Base, User):

    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer)

    def __init__(self, name, age):
        self.name = name
        self.age = age

在 Python 2 上运行具有此类层次结构的示例会产生以下错误:

TypeError:调用元类基础元类冲突时出错:派生类的元类必须是其所有基础元类的(非严格)子类

我相信这与YAMLObject元类有关......但我需要它,因为我也希望能够将这些对象保存为 YAML。对于我读到的关于这个错误的内容,我可能应该使用第三个元类,它继承自YAMLObject元类和Base,然后使用它来创建我想要的类......

class MetaMixinUser(type(User), type(Base)):
    pass

class SQLUser(six.with_metaclass(MetaMixinUser)):
    #[...]

不幸的是,这给出了另一个错误:

AttributeError:类型对象“SQLUser”没有属性“_decl_class_registry”

您能否指出我的推理存在缺陷的地方?

4

1 回答 1

1

如果您赶时间:从ruamel.yaml0.15.19 开始,您可以使用一条语句注册类YAMLObject,而无需子类化:

yaml = ruamel.yaml.YAML()
yaml.register_class(User)

YAMLObject是为了向后兼容 PyYAML,虽然它可能很方便,但我不推荐使用它,原因有以下三个:

  1. 它使您的类层次结构依赖于YAMLObject,正如您所注意到的,它可能会干扰其他依赖项
  2. Loader它默认使用不安全的
  3. 基于 Python 装饰器的解决方案将同样方便且侵入性更小。

子类化所做的唯一真实的事情YAMLObject是注册一个constructorfor thatyaml_tag和一个representerfor 子类。

所有示例都假设 from __future__ import print_function您运行 Python 2。

如果您有以下情况,基于子类化YAMLObject

import sys
import ruamel.yaml
from ruamel.std.pathlib import Path

yaml = ruamel.yaml.YAML(typ='unsafe')

class User(ruamel.yaml.YAMLObject):
    yaml_tag = u'user'

    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def to_yaml(cls, representer, node):
        return representer.represent_scalar(cls.yaml_tag, 
                                            u'{.name}-{.age}'.format(node, node))

    @classmethod
    def from_yaml(cls, constructor, node):
        # type: (Any, Any) -> Any
        return User(*node.value.split('-'))


data = {'users': [User('Anthon', 18)]}
yaml.dump(data, sys.stdout)
print()
tmp_file = Path('tmp.yaml')
yaml.dump(data, tmp_file)
rd = yaml.load(tmp_file)
print(rd['users'][0].name, rd['users'][0].age)

这会让你:

users: [!<user> Anthon-18]

Anthon 18

通过执行以下操作,您可以在不进行子类化的情况下获得完全相同的结果:

import sys
import ruamel.yaml
from ruamel.std.pathlib import Path

yaml = ruamel.yaml.YAML(typ='safe')

class User(object):
    yaml_tag = u'user'

    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def to_yaml(cls, representer, node):
        return representer.represent_scalar(cls.yaml_tag, 
                                            u'{.name}-{.age}'.format(node, node))

    @classmethod
    def from_yaml(cls, constructor, node):
        # type: (Any, Any) -> Any
        return User(*node.value.split('-'))


yaml.representer.add_representer(User, User.to_yaml)
yaml.constructor.add_constructor(User.yaml_tag, User.from_yaml)

data = {'users': [User('Anthon', 18)]}

yaml.dump(data, sys.stdout)
print()
tmp_file = Path('tmp.yaml')
yaml.dump(data, tmp_file)
rd = yaml.load(tmp_file)
print(rd['users'][0].name, rd['users'][0].age)

上面使用了SafeLoader(and SafeDumper),这是朝着正确方向迈出的一步。但是XXXX.add_YYY如果你有很多类,添加上面的行是很麻烦的,因为这些条目几乎但不完全相同。并且它不处理缺少任何一个或两者的类to_yamland from_yaml

要解决上述问题,我建议您yaml_object在文件中创建一个装饰器和一个辅助类myyaml.py

import ruamel.yaml

yaml = ruamel.yaml.YAML(typ='safe')

class SafeYAMLObject(object):
    def __init__(self, cls):
        self._cls = cls

    def to_yaml(self, representer, data):
        return representer.represent_yaml_object(
            self._cls.yaml_tag, data, self._cls,
            flow_style=representer.default_flow_style)

    def from_yaml(self, constructor, node):
        return constructor.construct_yaml_object(node, self._cls)

def yaml_object(cls):
    yaml.representer.add_representer(
        cls, getattr(cls, 'to_yaml', SafeYAMLObject(cls).to_yaml))
    yaml.constructor.add_constructor(
        cls.yaml_tag, getattr(cls, 'from_yaml', SafeYAMLObject(cls).from_yaml))
    return cls

有了它,你可以这样做:

import sys
from ruamel.std.pathlib import Path
from myyaml import yaml, yaml_object

@yaml_object
class User(object):
    yaml_tag = u'user'

    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def to_yaml(cls, representer, node):
        return representer.represent_scalar(cls.yaml_tag, 
                                            u'{.name}-{.age}'.format(node, node))

    @classmethod
    def from_yaml(cls, constructor, node):
        # type: (Any, Any) -> Any
        return User(*node.value.split('-'))


data = {'users': [User('Anthon', 18)]}

yaml.dump(data, sys.stdout)
print()
tmp_file = Path('tmp.yaml')
yaml.dump(data, tmp_file)
rd = yaml.load(tmp_file)
print(rd['users'][0].name, rd['users'][0].age)

再次得到相同的结果。如果您删除to_yamlandfrom_yaml方法,您将获得相同的最终值,但 YAML 略有不同:

users:
- !<user> {age: 18, name: Anthon}

Anthon 18

我无法对此进行测试,但是使用此装饰器而不是子类化YAMLObject应该可以摆脱以下TypeError情况:

class SQLUser(Base, User):

¹ 免责声明:我是ruamel.yaml此答案中使用的软件包的作者。
   免责声明 2:我并不是真正的 18 岁,但我确实遵循了 Brian Adams 在这张专辑的主打歌中表达的格言

于 2017-07-12T12:06:55.860 回答