如何使用Pony ORM存储Python Enum?

时间:2015-07-14 00:25:03

标签: python python-3.x orm enums ponyorm

说我在这里有这个简单的小POM ORM映射。从Python 3.4开始,内置的Enum类是新的,并且向后移植到2.7。

from enum import Enum

from pony.orm import Database, Required


class State(Enum):
    ready = 0
    running = 1
    errored = 2

if __name__ == '__main__':
    db = Database('sqlite', ':memory:', create_db=True)

    class StateTable(db.Entity):
        state = Required(State)

    db.generate_mapping(create_tables=True)

当我运行程序时,会抛出错误。

TypeError: No database converter found for type <enum 'State'>

这是因为Pony不支持映射枚举类型。当然,这里的解决方法是只存储Enum值,并在Class StateTable中提供一个getter,以便再次将值转换为Enum。但这很乏味且容易出错。我也可以使用另一个ORM。如果这个问题变得太令人头疼,也许我会的。但如果可以,我宁愿坚持使用Pony。

我更愿意创建一个数据库转换器来存储枚举,就像错误消息暗示一样。有谁知道怎么做?

更新: 感谢Ethan的帮助,我提出了以下解决方案。

from enum import Enum

from pony.orm import Database, Required, db_session
from pony.orm.dbapiprovider import StrConverter


class State(Enum):
    ready = 0
    running = 1
    errored = 2

class EnumConverter(StrConverter):

    def validate(self, val):
        if not isinstance(val, Enum):
            raise ValueError('Must be an Enum.  Got {}'.format(type(val)))
        return val

    def py2sql(self, val):
        return val.name

    def sql2py(self, value):
        # Any enum type can be used, so py_type ensures the correct one is used to create the enum instance
        return self.py_type[value]

if __name__ == '__main__':
    db = Database('sqlite', ':memory:', create_db=True)

    # Register the type converter with the database
    db.provider.converter_classes.append((Enum, EnumConverter))

    class StateTable(db.Entity):
        state = Required(State)

    db.generate_mapping(create_tables=True)

    with db_session:
        s = StateTable(state=State.ready)
        print('Got {} from db'.format(s.state))

1 个答案:

答案 0 :(得分:11)

Excerpt from some random mailing list

  

2.2。转换器方法

     

每个转换器类应定义以下方法:

class MySpecificConverter(Converter):

    def init(self, kwargs):
        # Override this method to process additional positional
        # and keyword arguments of the attribute

       if self.attr is not None:
            # self.attr.args can be analyzed here
            self.args = self.attr.args

        self.my_optional_argument = kwargs.pop("kwarg_name")
        # You should take all valid options from this kwargs
        # What is left in is regarded as unrecognized option

    def validate(self, val):
        # convert value to the necessary type (e.g. from string)
        # validate all necessary constraints (e.g. min/max bounds)
        return val

    def py2sql(self, val):
        # prepare the value (if necessary) to storing in the database
        return val

    def sql2py(self, value):
        # convert value (if necessary) after the reading from the db
        return val

    def sql_type(self):
        # generate corresponding SQL type, based on attribute options
        return "SOME_SQL_TYPE_DEFINITION"
     

您可以研究现有转换器的代码,看看这些方法如何   实施。