元类应用ORM实现

Posted sunlong88

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了元类应用ORM实现相关的知识,希望对你有一定的参考价值。

首先看下一个简单的例子

# 需求
import numbers


class Field:
    pass

class IntField(Field):
    # 数据描述符
    def __init__(self, db_column, min_value=None, max_value=None):
        self._value = None
        self.min_value = min_value
        self.max_value = max_value
        self.db_column = db_column
        if min_value is not None:
            if not isinstance(min_value, numbers.Integral):
                raise ValueError("min_value must be int")
            elif min_value < 0:
                raise ValueError("min_value must be positive int")
        if max_value is not None:
            if not isinstance(max_value, numbers.Integral):
                raise ValueError("max_value must be int")
            elif max_value < 0:
                raise ValueError("max_value must be positive int")
        if min_value is not None and max_value is not None:
            if min_value > max_value:
                raise ValueError("min_value must be smaller than max_value")

    def __get__(self, instance, owner):
        return self._value

    def __set__(self, instance, value):
        if not isinstance(value, numbers.Integral):
            raise ValueError("int value need")
        if value < self.min_value or value > self.max_value:
            raise ValueError("value must between min_value and max_value")
        self._value = value


class CharField(Field):
    def __init__(self, db_column, max_length=None):
        self._value = None
        self.db_column = db_column
        if max_length is None:
            raise ValueError("you must spcify max_lenth for charfiled")
        self.max_length = max_length

    def __get__(self, instance, owner):
        return self._value

    def __set__(self, instance, value):
        if not isinstance(value, str):
            raise ValueError("string value need")
        if len(value) > self.max_length:
            raise ValueError("value len excess len of max_length")
        self._value = value

 

上述为属性描述符

 

元类的应用

class ModelMetaClass(type):
    def __new__(cls, *args, **kwargs):
        return super().__new__(cls, *args, **kwargs)

class BaseModel(metaclass=ModelMetaClass):
    def __init__(self,*args,**kwargs):
        for key,value in kwargs.items():
            setattr(self,key,value)
        # return super().__init__()

class User(BaseModel):
    name  = CharField(db_column="name", max_length=10)
    age = IntField(db_column="age", min_value=1, max_value=100)

    class Meta:
        db_table = ‘user‘

if __name__ == "__main__":
    user = User(name="bobby", age=28)
    # user.name = "bobby"
    # user.age = 28
    # user.save()
    print(user.name)
    print(user.age)
    print(user.Meta)

执行后结果:

bobby
28
<class ‘__main__.User.Meta‘>

 

进一步改进代码:

class ModelMetaClass(type):
    """
    name 类名
    bases 基类(元组)
    attrs:属性
    还记得下面type生成类的使用方法吗?
    User = type("User", (BaseClass, ), {"name":"user", "say":say})
    """
    def __new__(cls, name, bases, attrs, **kwargs):
        if name == "BaseModel":
            return super().__new__(cls, name, bases, attrs, **kwargs)
        fields = {}
        for key,value in attrs.items():
            if isinstance(value,Field):
                fields[key] = value
        attrs_meta = attrs.get(‘Meta‘,None)
        _meta = {}
        db_table = name.lower()
        if attrs_meta is not None:
            table = getattr(attrs_meta,‘db_table‘,None)
            if table is not None:
                db_table = table
        _meta[‘db_table‘] = db_table
        attrs[‘_meta‘] = _meta
        attrs[‘fields‘] = fields
        del attrs["Meta"]
        return super().__new__(cls, name, bases, attrs, **kwargs)

class BaseModel(metaclass=ModelMetaClass):
    def __init__(self,*args,**kwargs):
        for key,value in kwargs.items():
            setattr(self,key,value)
        # return super().__init__()

class User(BaseModel):
    name  = CharField(db_column="name", max_length=10)
    age = IntField(db_column="age", min_value=1, max_value=100)

    class Meta:
        db_table = ‘user‘

if __name__ == "__main__":
    user = User(name="bobby", age=28)
    # user.name = "bobby"
    # user.age = 28
    # user.save()
    print(user.name)
    print(user.age)
    print(user._meta)
    print(user.fields)

执行结果:

bobby
28
{‘db_table‘: ‘user‘}
{‘age‘: <__main__.IntField object at 0x0000000000C1F438>, ‘name‘: <__main__.CharField object at 0x0000000000C1F3C8>}

 






以上是关于元类应用ORM实现的主要内容,如果未能解决你的问题,请参考以下文章

元类实现ORM

Python元类实现ORM框架

Python 元类实现ORM

35.Python面向对象元类:type()__metaclass__属性实现简易ORM框架

35.Python面向对象元类:type()__metaclass__属性实现简易ORM框架

35.Python面向对象元类:type()__metaclass__属性实现简易ORM框架